Java Code Examples for java.util.Collections.min()

The following are Jave code examples for showing how to use min() of the java.util.Collections class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: javaide   File: FindMinimumOfHashSetExample.java   View Source Code Vote up 6 votes
public static void main(String[] args) {

    //create a HashSet object
    HashSet hashSet = new HashSet();

    //Add elements to HashSet
    hashSet.add(new Long("923740927"));
    hashSet.add(new Long("4298748382"));
    hashSet.add(new Long("2374324832"));
    hashSet.add(new Long("2473483643"));
    hashSet.add(new Long("32987432984"));

    /*
       To find minimum element of Java HashSet use,
       static Object min(Collection c) method of Collections class.

       This method returns the minimum element of Java HashSet according to
       its natural ordering.
    */

    Object obj = Collections.min(hashSet);

    System.out.println("Minimum Element of Java HashSet is : " + obj);
  }
 
Example 2
Project: deisotoper   File: Configuration.java   View Source Code Vote up 6 votes
public Configuration(Map<String, Double> aaMass, double delta, double errortolerance, double distance, double noise,
        boolean decharge, String modus) {
    this.delta = delta;
    this.errortolerance = errortolerance;
    this.distance = distance;
    this.noise = noise;
    this.decharge = decharge;
    this.aaMass = aaMass;
    this.modus = modus;

    for (Map.Entry<String, Double> entry : aaMass.entrySet()) {
        this.aaMassDividedTwo.put(entry.getKey(), entry.getValue() / 2);
        this.aaMassDividedThree.put(entry.getKey(), entry.getValue() / 3);
    }

    this.minimum = Collections.min(this.aaMassDividedThree.values());
    this.maximum = Collections.max(this.aaMass.values());
}
 
Example 3
Project: face-landmark-android   File: CameraConnectionFragment.java   View Source Code Vote up 6 votes
/**
 * Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose
 * width and height are at least as large as the respective requested values, and whose aspect
 * ratio matches with the specified value.
 *
 * @param choices     The list of sizes that the camera supports for the intended output class
 * @param width       The minimum desired width
 * @param height      The minimum desired height
 * @param aspectRatio The aspect ratio
 * @return The optimal {@code Size}, or an arbitrary one if none were big enough
 */
@SuppressLint("LongLogTag")
@DebugLog
private static Size chooseOptimalSize(
        final Size[] choices, final int width, final int height, final Size aspectRatio) {
    // Collect the supported resolutions that are at least as big as the preview Surface
    final List<Size> bigEnough = new ArrayList<Size>();
    for (final Size option : choices) {
        if (option.getHeight() >= MINIMUM_PREVIEW_SIZE && option.getWidth() >= MINIMUM_PREVIEW_SIZE) {
            Log.i(TAG, "Adding size: " + option.getWidth() + "x" + option.getHeight());
            bigEnough.add(option);
        } else {
            Log.i(TAG, "Not adding size: " + option.getWidth() + "x" + option.getHeight());
        }
    }

    // Pick the smallest of those, assuming we found any
    if (bigEnough.size() > 0) {
        final Size chosenSize = Collections.min(bigEnough, new CompareSizesByArea());
        Log.i(TAG, "Chosen size: " + chosenSize.getWidth() + "x" + chosenSize.getHeight());
        return chosenSize;
    } else {
        Log.e(TAG, "Couldn't find any suitable preview size");
        return choices[0];
    }
}
 
Example 4
Project: KingdomFactions   File: NexusModule.java   View Source Code Vote up 6 votes
public INexus getClosestNexus(KingdomFactionsPlayer player) {
	HashMap<INexus, Double> distance = new HashMap<INexus, Double>();
	for (INexus n : NexusModule.getInstance().getNexuses()) {
		Location nexusloc = Utils.getInstance().getNewLocation(getLoc(n));
		Location playerloc = Utils.getInstance().getNewLocation(player.getLocation());
		nexusloc.setY(0);
		playerloc.setY(0);
		distance.put(n, nexusloc.distance(playerloc));
	}
	double minValueInMap = (Collections.min(distance.values()));
	if (distance.isEmpty()) {
		return null;
	}
	for (Entry<INexus, Double> entry : distance.entrySet()) {
		if (entry.getValue() == minValueInMap) {
			entry.getKey(); // nexus
			entry.getValue();// value
			return entry.getKey();

		}
	}
	return null;
}
 
Example 5
Project: quidditchtimekeeper   File: GameActivity.java   View Source Code Vote up 6 votes
public List<Integer> getMinIndizes(List<Long> arrayList)
{
    if(arrayList.size() > 0)
    {
        long delta_time = 100; // in ms
        long minTime = Collections.min(arrayList);
        if(minTime!=maxlong)//if minTime == maxint there are no reducible penalties
        {
            List<Integer> minInd = new ArrayList<>();
            for(int i=0;i<arrayList.size();i++)
            {
                if(arrayList.get(i)<=minTime+delta_time) minInd.add(i);
            }
            return minInd;
        }
    }
    return new ArrayList<>();
}
 
Example 6
Project: AI-RRT-Motion-Planning   File: Obstacle.java   View Source Code Vote up 6 votes
/**
 * Constructs an obstacle from the representation used in the input file:
 * that is, the x- and y- coordinates of all of the corners of the
 * rectangle.
 * 
 * @param str
 */
public Obstacle(String str) {
	Scanner s = new Scanner(str);
	List<Double> xs = new ArrayList<Double>();
	List<Double> ys = new ArrayList<Double>();
	for (int i = 0; i < 4; i++) {
		xs.add(s.nextDouble());
		ys.add(s.nextDouble());
	}
	double xMin = Collections.min(xs);
	double xMax = Collections.max(xs);
	double yMin = Collections.min(ys);
	double yMax = Collections.max(ys);
	this.rect = new Rectangle2D.Double(xMin, yMin, xMax - xMin, yMax - yMin);
	s.close();
}
 
Example 7
Project: featurea   File: Rectangle.java   View Source Code Vote up 5 votes
public double left() {
    if (isTile()) {
        return x1;
    } else {
        return Collections.min(Arrays.asList(x1, x2, x3, x4));
    }
}
 
Example 8
Project: VideoCRE   File: CameraEnumerationAndroid.java   View Source Code Vote up 5 votes
public static CaptureFormat.FramerateRange getClosestSupportedFramerateRange(
    List<CaptureFormat.FramerateRange> supportedFramerates, final int requestedFps) {
  return Collections.min(
      supportedFramerates, new ClosestComparator<CaptureFormat.FramerateRange>() {
        // Progressive penalty if the upper bound is further away than |MAX_FPS_DIFF_THRESHOLD|
        // from requested.
        private static final int MAX_FPS_DIFF_THRESHOLD = 5000;
        private static final int MAX_FPS_LOW_DIFF_WEIGHT = 1;
        private static final int MAX_FPS_HIGH_DIFF_WEIGHT = 3;

        // Progressive penalty if the lower bound is bigger than |MIN_FPS_THRESHOLD|.
        private static final int MIN_FPS_THRESHOLD = 8000;
        private static final int MIN_FPS_LOW_VALUE_WEIGHT = 1;
        private static final int MIN_FPS_HIGH_VALUE_WEIGHT = 4;

        // Use one weight for small |value| less than |threshold|, and another weight above.
        private int progressivePenalty(int value, int threshold, int lowWeight, int highWeight) {
          return (value < threshold) ? value * lowWeight
                                     : threshold * lowWeight + (value - threshold) * highWeight;
        }

        @Override
        int diff(CaptureFormat.FramerateRange range) {
          final int minFpsError = progressivePenalty(
              range.min, MIN_FPS_THRESHOLD, MIN_FPS_LOW_VALUE_WEIGHT, MIN_FPS_HIGH_VALUE_WEIGHT);
          final int maxFpsError = progressivePenalty(Math.abs(requestedFps * 1000 - range.max),
              MAX_FPS_DIFF_THRESHOLD, MAX_FPS_LOW_DIFF_WEIGHT, MAX_FPS_HIGH_DIFF_WEIGHT);
          return minFpsError + maxFpsError;
        }
      });
}
 
Example 9
Project: Image-Detection-Samples   File: FDCamera2Presenter.java   View Source Code Vote up 5 votes
private static Size chooseOptimalSize(Size[] choices, int textureViewWidth,
                                      int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio) {

    // Collect the supported resolutions that are at least as big as the preview Surface
    List<Size> bigEnough = new ArrayList<>();
    // Collect the supported resolutions that are smaller than the preview Surface
    List<Size> notBigEnough = new ArrayList<>();
    int w = aspectRatio.getWidth();
    int h = aspectRatio.getHeight();
    for (Size option : choices) {
        if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
                option.getHeight() == option.getWidth() * h / w) {
            if (option.getWidth() >= textureViewWidth &&
                    option.getHeight() >= textureViewHeight) {
                bigEnough.add(option);
            } else {
                notBigEnough.add(option);
            }
        }
    }

    // Pick the smallest of those big enough. If there is no one big enough, pick the
    // largest of those not big enough.
    if (bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else if (notBigEnough.size() > 0) {
        return Collections.max(notBigEnough, new CompareSizesByArea());
    } else {
        Log.e(TAG, "Couldn't find any suitable preview size");
        return choices[0];
    }
}
 
Example 10
Project: educational-plugin   File: CCDeactivatePlaceholder.java   View Source Code Vote up 5 votes
protected boolean isAvailable(TaskFile taskFile, int offset) {
  AnswerPlaceholder existingActivePlaceholder = taskFile.getAnswerPlaceholder(offset);
  if (existingActivePlaceholder == null) {
    return false;
  }
  final Task task = taskFile.getTask();
  return task instanceof TaskWithSubtasks &&
         Collections.min(existingActivePlaceholder.getSubtaskInfos().keySet()) < ((TaskWithSubtasks)task).getActiveSubtaskIndex();
}
 
Example 11
Project: s-store   File: HStoreSite.java   View Source Code Vote up 4 votes
/**
 * Take snapshots
 */
private void takeSnapshot(){
    // Do this only on site lowest id
    Host catalog_host = this.getHost();
    Site site = this.getSite();

    Integer lowest_site_id = Integer.MAX_VALUE, s_id;

    for (Site st : CatalogUtil.getAllSites(catalog_host)) {
        s_id = st.getId();
        lowest_site_id = Math.min(s_id, lowest_site_id);
    }

    int m_siteId = this.getSiteId();
    
    if (m_siteId == lowest_site_id) {
        LOG.warn("Taking snapshot at site "+m_siteId);

        VoltTable[] results = null;
        try {
            File snapshotDir = this.getSnapshotDir();
            String path = snapshotDir.getAbsolutePath();

            java.util.Date date = new java.util.Date();
            Timestamp current = new Timestamp(date.getTime());
            String nonce = Long.toString(current.getTime());

            CatalogContext cc = this.getCatalogContext();
            String procName = VoltSystemProcedure.procCallName(SnapshotSave.class);
            Procedure catalog_proc = cc.procedures.getIgnoreCase(procName);

            ParameterSet params = new ParameterSet();
            params.setParameters(
                    path,  // snapshot dir
                    nonce, // nonce - timestamp
                    1      // block
                    );

            int base_partition = Collections.min(this.local_partitions);

            RpcCallback<ClientResponseImpl> callback = new RpcCallback<ClientResponseImpl>() {
                @Override
                public void run(ClientResponseImpl parameter) {
                    // Do nothing!
                }
            };
            
            LocalTransaction ts = this.txnInitializer.createLocalTransaction(
                    -1, //TODO: This is just a hack, needs an actual batchID
            		null, 
                    EstTime.currentTimeMillis(), 
                    99999999, 
                    base_partition, 
                    catalog_proc, 
                    params, 
                    callback
                    );

            LOG.warn("Queuing snapshot transaction : base partition : "+base_partition+" path :"+ path + " nonce :"+ nonce);

            // Queue @SnapshotSave transaction
            this.transactionQueue(ts);

        } catch (Exception ex) {
            ex.printStackTrace();
            LOG.fatal("SnapshotSave exception: " + ex.getMessage());
            this.hstore_coordinator.shutdown();
        }
    }        
    
}
 
Example 12
Project: ditb   File: HRegion.java   View Source Code Vote up 4 votes
@Override public long getEarliestFlushTimeForAllStores() {
  return lastStoreFlushTimeMap.isEmpty() ?
      Long.MAX_VALUE :
      Collections.min(lastStoreFlushTimeMap.values());
}
 
Example 13
Project: util   File: CollectionUtil.java   View Source Code Vote up 4 votes
/**
 * 返回无序集合中的最小值,使用元素默认排序
 */
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
	return Collections.min(coll);
}
 
Example 14
Project: CameraKitView   File: Camera2Fragment.java   View Source Code Vote up 4 votes
/**
 * Given {@code choices} of {@code Size}s supported by a camera, choose the smallest one that
 * is at least as large as the respective texture view size, and that is at most as large as the
 * respective max size, and whose aspect ratio matches with the specified value. If such size
 * doesn't exist, choose the largest one that is at most as large as the respective max size,
 * and whose aspect ratio matches with the specified value.
 *
 * @param choices           The list of sizes that the camera supports for the intended output
 *                          class
 * @param textureViewWidth  The width of the texture view relative to sensor coordinate
 * @param textureViewHeight The height of the texture view relative to sensor coordinate
 * @param maxWidth          The maximum width that can be chosen
 * @param maxHeight         The maximum height that can be chosen
 * @return The optimal {@code Size}, or an arbitrary one if none were big enough
 */
Size chooseOptimalSize(Size[] choices, int textureViewWidth,
                       int textureViewHeight, int maxWidth, int maxHeight) {
    mPreviewSizes.clear();
    // Collect the supported resolutions that are at least as big as the preview Surface
    List<Size> bigEnough = new ArrayList<>();
    // Collect the supported resolutions that are smaller than the preview Surface
    List<Size> notBigEnough = new ArrayList<>();
    int w = mAspectRatio.getX();
    int h = mAspectRatio.getY();
    for (Size option : choices) {
        if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight) {
            mPreviewSizes.add(new cn.lytcom.cameraview.Size(option.getWidth(), option.getHeight()));
            if (option.getHeight() == option.getWidth() * h / w) {
                if (option.getWidth() >= textureViewWidth &&
                    option.getHeight() >= textureViewHeight) {
                    bigEnough.add(option);
                } else {
                    notBigEnough.add(option);
                }
            }
        }
    }

    // Pick the smallest of those big enough. If there is no one big enough, pick the
    // largest of those not big enough.
    if (bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else if (notBigEnough.size() > 0) {
        return Collections.max(notBigEnough, new CompareSizesByArea());
    } else {
        Log.e(TAG, "Couldn't find any suitable preview size");
        mAspectRatio = AspectRatio.of(4, 3);
        SortedSet<cn.lytcom.cameraview.Size> sortedSet = mPreviewSizes.sizes(mAspectRatio);
        if (sortedSet != null) {
            cn.lytcom.cameraview.Size lastSize = sortedSet.last();
            return new Size(lastSize.getWidth(), lastSize.getHeight());
        }
        mAspectRatio = AspectRatio.of(choices[0].getWidth(), choices[0].getHeight());
        return choices[0];
    }
}
 
Example 15
Project: athena   File: SegmentRoutingManager.java   View Source Code Vote up 4 votes
/**
 * Returns the vlan-id assigned to the subnet configured for a device.
 * If no vlan-id has been assigned, a new one is assigned out of a pool of ids,
 * if and only if this controller instance is the master for the device.
 * <p>
 * USAGE: The assigned vlans are meant to be applied to untagged packets on those
 * switches/pipelines that need this functionality. These vids are meant
 * to be used internally within a switch, and thus need to be unique only
 * on a switch level. Note that packets never go out on the wire with these
 * vlans. Currently, vlan ids are assigned from value 4093 down.
 * Vlan id 4094 expected to be used for all ports that are not assigned subnets.
 * Vlan id 4095 is reserved and unused. Only a single vlan id is assigned
 * per subnet.
 *
 * @param deviceId switch dpid
 * @param subnet IPv4 prefix for which assigned vlan is desired
 * @return VlanId assigned for the subnet on the device, or
 *         null if no vlan assignment was found and this instance is not
 *         the master for the device.
 */
// TODO: We should avoid assigning VLAN IDs that are used by VLAN cross-connection.
public VlanId getSubnetAssignedVlanId(DeviceId deviceId, Ip4Prefix subnet) {
    VlanId assignedVid = subnetVidStore.get(new SubnetAssignedVidStoreKey(
                                                    deviceId, subnet));
    if (assignedVid != null) {
        log.debug("Query for subnet:{} on device:{} returned assigned-vlan "
                + "{}", subnet, deviceId, assignedVid);
        return assignedVid;
    }
    //check mastership for the right to assign a vlan
    if (!mastershipService.isLocalMaster(deviceId)) {
        log.warn("This controller instance is not the master for device {}. "
                + "Cannot assign vlan-id for subnet {}", deviceId, subnet);
        return null;
    }
    // vlan assignment is expensive but done only once
    Set<Ip4Prefix> configuredSubnets = deviceConfiguration.getSubnets(deviceId);
    Set<Short> assignedVlans = new HashSet<>();
    Set<Ip4Prefix> unassignedSubnets = new HashSet<>();
    for (Ip4Prefix sub : configuredSubnets) {
        VlanId v = subnetVidStore.get(new SubnetAssignedVidStoreKey(deviceId,
                                                                    sub));
        if (v != null) {
            assignedVlans.add(v.toShort());
        } else {
            unassignedSubnets.add(sub);
        }
    }
    short nextAssignedVlan = ASSIGNED_VLAN_START;
    if (!assignedVlans.isEmpty()) {
        nextAssignedVlan = (short) (Collections.min(assignedVlans) - 1);
    }
    for (Ip4Prefix unsub : unassignedSubnets) {
        // Special case for default route. Assign default VLAN ID to /32 and /0 subnets
        if (unsub.prefixLength() == IpPrefix.MAX_INET_MASK_LENGTH ||
                unsub.prefixLength() == 0) {
            subnetVidStore.put(new SubnetAssignedVidStoreKey(deviceId, unsub),
                    VlanId.vlanId(ASSIGNED_VLAN_NO_SUBNET));
        } else {
            subnetVidStore.put(new SubnetAssignedVidStoreKey(deviceId, unsub),
                    VlanId.vlanId(nextAssignedVlan--));
            log.info("Assigned vlan: {} to subnet: {} on device: {}",
                    nextAssignedVlan + 1, unsub, deviceId);
        }
    }

    return subnetVidStore.get(new SubnetAssignedVidStoreKey(deviceId, subnet));
}
 
Example 16
Project: util   File: CollectionUtil.java   View Source Code Vote up 4 votes
/**
 * 返回无序集合中的最小值
 */
public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {
	return Collections.min(coll, comp);
}
 
Example 17
Project: weex-3d-map   File: HighLevelEncoder.java   View Source Code Vote up 4 votes
/**
 * @return text represented by this encoder encoded as a {@link BitArray}
 */
public BitArray encode() {
  Collection<State> states = Collections.singletonList(State.INITIAL_STATE);
  for (int index = 0; index < text.length; index++) {
    int pairCode;
    int nextChar = index + 1 < text.length ? text[index + 1] : 0;
    switch (text[index]) {
      case '\r':  
        pairCode = nextChar == '\n' ? 2 : 0; 
        break;
      case '.' :  
        pairCode = nextChar == ' '  ? 3 : 0; 
        break;
      case ',' :  
        pairCode = nextChar == ' ' ? 4 : 0; 
        break;
      case ':' :  
        pairCode = nextChar == ' ' ? 5 : 0; 
        break;
      default:    
        pairCode = 0;
    }
    if (pairCode > 0) {
      // We have one of the four special PUNCT pairs.  Treat them specially.
      // Get a new set of states for the two new characters.
      states = updateStateListForPair(states, index, pairCode);
      index++;
    } else {
      // Get a new set of states for the new character.
      states = updateStateListForChar(states, index);
    }
  }
  // We are left with a set of states.  Find the shortest one.
  State minState = Collections.min(states, new Comparator<State>() {
    @Override
    public int compare(State a, State b) {
      return a.getBitCount() - b.getBitCount();
    }
  });
  // Convert it to a bit array, and return.
  return minState.toBitArray(text);
}
 
Example 18
Project: SpotSpotter   File: GetMaxMinMidAvg.java   View Source Code Vote up 4 votes
public static double[] getMAXMINFromList(List list) {
	final double max = (double) Collections.max(list);
	final double min = (double) Collections.min(list);
	final double[] set = {max, min};
	return set;
}
 
Example 19
Project: sstore-soft   File: VoltSystemProcedure.java   View Source Code Vote up 2 votes
/**
 * Helper method that will return true if the invoking partition
 * is the first partition at this HStoreSite
 * @return
 */
protected final boolean isFirstLocalPartition() {
    return (Collections.min(hstore_site.getLocalPartitionIds()) == this.partitionId);
}
 
Example 20
Project: s-store   File: VoltSystemProcedure.java   View Source Code Vote up 2 votes
/**
 * Helper method that will return true if the invoking partition
 * is the first partition at this HStoreSite
 * @return
 */
protected final boolean isFirstLocalPartition() {
    return (Collections.min(hstore_site.getLocalPartitionIds()) == this.partitionId);
}