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

The following examples show how to use java.util.Collections#min() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CameraController.java    From KrGallery with GNU General Public License v2.0 6 votes vote down vote up
public static Size chooseOptimalSize(List<Size> choices, int width, int height, Size aspectRatio) {
    List<Size> bigEnough = new ArrayList<>();
    int w = aspectRatio.getWidth();
    int h = aspectRatio.getHeight();
    for (int a = 0; a < choices.size(); a++) {
        Size option = choices.get(a);
        if (option.getHeight() == option.getWidth() * h / w && option.getWidth() >= width && option.getHeight() >= height) {
            bigEnough.add(option);
        }
    }
    if (bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else {
        return Collections.max(choices, new CompareSizesByArea());
    }
}
 
Example 2
Source File: KafkaFlatTableJob.java    From kylin with Apache License 2.0 6 votes vote down vote up
private void setupMapper(CubeSegment cubeSeg) throws IOException {
    // set the segment's offset info to job conf
    Map<Integer, Long> offsetStart = cubeSeg.getSourcePartitionOffsetStart();
    Map<Integer, Long> offsetEnd = cubeSeg.getSourcePartitionOffsetEnd();

    Integer minPartition = Collections.min(offsetStart.keySet());
    Integer maxPartition = Collections.max(offsetStart.keySet());
    job.getConfiguration().set(CONFIG_KAFKA_PARITION_MIN, minPartition.toString());
    job.getConfiguration().set(CONFIG_KAFKA_PARITION_MAX, maxPartition.toString());

    for(Integer partition: offsetStart.keySet()) {
        job.getConfiguration().set(CONFIG_KAFKA_PARITION_START + partition, offsetStart.get(partition).toString());
        job.getConfiguration().set(CONFIG_KAFKA_PARITION_END + partition, offsetEnd.get(partition).toString());
    }

    job.setMapperClass(KafkaFlatTableMapper.class);
    job.setInputFormatClass(KafkaInputFormat.class);
    job.setOutputKeyClass(BytesWritable.class);
    job.setOutputValueClass(Text.class);
    job.setOutputFormatClass(SequenceFileOutputFormat.class);
}
 
Example 3
Source File: AutoConfig.java    From tomee with Apache License 2.0 6 votes vote down vote up
private String firstMatching(final String prefix, final String type, final Properties required, final AppResources appResources) {
    final List<String> resourceIds = getResourceIds(appResources, type, required);
    if(resourceIds.isEmpty()){
        return null;
    }

    return Collections.min(resourceIds, new Comparator<String>() { // sort from webapp to global resources
        @Override
        public int compare(final String o1, final String o2) { // don't change global order, just put app scoped resource before others
            if (o1.startsWith(prefix) && o2.startsWith(prefix)) {
                return resourceIds.indexOf(o1) - resourceIds.indexOf(o2);
            } else if (o1.startsWith(prefix)) {
                return -1;
            } else if (o2.startsWith(prefix)) {
                return 1;
            }
            // make it stable with prefixed comparison + keep existing ordering (bck compat)
            return resourceIds.indexOf(o1) - resourceIds.indexOf(o2);
        }
    });
}
 
Example 4
Source File: TestConstraintRebalanceStrategy.java    From helix with Apache License 2.0 6 votes vote down vote up
@Test
public void testEvennessByDefaultConstraint() {
  Map<String, Map<String, Map<String, String>>> result = new HashMap<>();

  ConstraintRebalanceStrategy strategy = new ConstraintRebalanceStrategy();

  for (String resourceName : resourceNames) {
    Map<String, Map<String, String>> partitionMap = new HashMap<>();

    strategy.init(resourceName, partitions, states, Integer.MAX_VALUE);
    partitionMap.putAll(strategy.computePartitionAssignment(instanceNames, instanceNames,
        new HashMap<String, Map<String, String>>(), cache).getMapFields());
    result.put(resourceName, partitionMap);
  }

  Map<String, Integer> weightCount = checkPartitionUsage(result, new PartitionWeightProvider() {
    @Override
    public int getPartitionWeight(String resource, String partition) {
      return 1;
    }
  });
  int max = Collections.max(weightCount.values());
  int min = Collections.min(weightCount.values());
  // Since the accuracy of Default evenness constraint is 0.01, diff should be 1/100 of participant capacity in max.
  Assert.assertTrue((max - min) <= defaultCapacity / 100);
}
 
Example 5
Source File: BorderDrawable.java    From ucar-weex-core with Apache License 2.0 6 votes vote down vote up
private float getScaleFactor(@NonNull RectF borderBox) {
  final float topRadius = getBorderRadius(mBorderRadius, BORDER_TOP_LEFT_RADIUS)
                          + getBorderRadius(mBorderRadius, BORDER_TOP_RIGHT_RADIUS);
  final float rightRadius = getBorderRadius(mBorderRadius, BORDER_TOP_RIGHT_RADIUS)
                            + getBorderRadius(mBorderRadius, BORDER_BOTTOM_RIGHT_RADIUS);
  final float bottomRadius = getBorderRadius(mBorderRadius, BORDER_BOTTOM_RIGHT_RADIUS)
                             + getBorderRadius(mBorderRadius, BORDER_BOTTOM_LEFT_RADIUS);
  final float leftRadius = getBorderRadius(mBorderRadius, BORDER_BOTTOM_LEFT_RADIUS)
                           + getBorderRadius(mBorderRadius, BORDER_TOP_LEFT_RADIUS);
  List<Float> factors = new ArrayList<>(4);
  updateFactor(factors, borderBox.width(), topRadius);
  updateFactor(factors, borderBox.height(), rightRadius);
  updateFactor(factors, borderBox.width(), bottomRadius);
  updateFactor(factors, borderBox.height(), leftRadius);
  float factor;
  if (factors.isEmpty()) {
    factor = Float.NaN;
  } else {
    factor = Collections.min(factors);
  }
  return factor;
}
 
Example 6
Source File: GibberishDetector.java    From Gibberish-Detector-Java with MIT License 6 votes vote down vote up
private void train(List<String> trainingLinesList, List<String> goodLinesList, List<String> badLinesList) {
	initializePositionMap();
	
	int[][] alphabetCouplesMatrix = getAlphaBetCouplesMatrix(trainingLinesList);
	logProbabilityMatrix = getLogProbabilityMatrix(alphabetCouplesMatrix);
		
	List<Double> goodProbability = getAvgTransitionProbability(goodLinesList, logProbabilityMatrix);
	List<Double> badProbability = getAvgTransitionProbability(badLinesList, logProbabilityMatrix);
	
	double minGood = Collections.min(goodProbability);
	double maxBad = Collections.max(badProbability);
			
	if (minGood <= maxBad) {
		throw new AssertionError("cannot create a threshold");
	}
	threshold = getThreshold(minGood, maxBad);
}
 
Example 7
Source File: PostingsExplorerQuery.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
@Override
public float score() throws IOException {
    if (this.postingsEnum.freq() <= 0) {
        return 0.0f;
    }

    ArrayList<Float> positions = new ArrayList<Float>();
    for (int i=0;i<this.postingsEnum.freq();i++){
        positions.add((float) this.postingsEnum.nextPosition() + 1);
    }

    float retval;
    switch(this.typeConditional) {
        case("avg_raw_tp"):
            float sum = 0.0f;
            for (float position : positions) {
                sum += position;
            }
            retval = sum / positions.size();
            break;
        case("max_raw_tp"):
            retval = Collections.max(positions);
            break;
        case("min_raw_tp"):
            retval = Collections.min(positions);
            break;
        default:
            retval = 0.0f;
    }

    return retval;
}
 
Example 8
Source File: Either.java    From docopt.java with MIT License 5 votes vote down vote up
@Override
protected MatchResult match(final List<LeafPattern> left,
		List<LeafPattern> collected) {
	if (collected == null) {
		collected = list();
	}

	final List<MatchResult> outcomes = list();

	for (final Pattern pattern : getChildren()) {
		final MatchResult m = pattern.match(left, collected);
		if (m.matched()) {
			outcomes.add(m);
		}
	}

	if (!outcomes.isEmpty()) {
		// >>> return min(outcomes, key=lambda outcome: len(outcome[1]))
		{
			return Collections.min(outcomes, new Comparator<MatchResult>() {

				@Override
				public int compare(final MatchResult o1,
						final MatchResult o2) {
					final Integer s1 = Integer.valueOf(o1.getLeft().size());
					final Integer s2 = Integer.valueOf(o2.getLeft().size());
					return s1.compareTo(s2);
				}
			});
		}
	}

	return new MatchResult(false, left, collected);
}
 
Example 9
Source File: OffensePlanner.java    From open-ig with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Check if a fleet is in upgrade position over a planet.
 * @param cruisers the list of cruiser/destroyer technology ordered by expense
 * @param battleships the list of battleships ordered by expense
 * @return true if action taken
 */
boolean checkDeploy(final List<ResearchType> cruisers,
		final List<ResearchType> battleships) {

	List<AIFleet> upgradeTasks = findFleetsWithTask(FleetTask.UPGRADE, new Pred1<AIFleet>() {
		@Override
		public Boolean invoke(AIFleet value) {
			return !value.isMoving() && value.statistics.planet != null;
		}
	});
	if (upgradeTasks.isEmpty()) {
           return !findFleetsWithTask(FleetTask.UPGRADE, null).isEmpty();
       }
	
	final Fleet fleet = Collections.min(upgradeTasks, firepowerAsc).fleet;
	
	final int cl = world.cruiserLimit;
	final int bl = world.battleshipLimit;
	
	add(new Action0() {
		@Override
		public void invoke() {
			if (fleet.task == FleetTask.SCRIPT) {
				return;
			}
			fleet.upgradeAll();
			if (!cruisers.isEmpty()) {
				fleet.replaceWithShip(cruisers.get(0), cl);
			}
			if (!battleships.isEmpty()) {
				fleet.replaceWithShip(battleships.get(0), bl);
			}
			fleet.task = FleetTask.IDLE;
			log("UpgradeFleet, Fleet = %s (%d)", fleet.name(), fleet.id);
		}
	});
	
	return true;
}
 
Example 10
Source File: CopyRatioData.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CopyRatioData(final SegmentedGenome segmentedGenome) {
    final TargetCollection<ReadCountRecord.SingleSampleRecord> targetCoverages = segmentedGenome.getGenome().getTargets();
    Utils.validateArg(targetCoverages.targetCount() > 0, "Cannot construct CopyRatioData with no target-coverage data.");
    //construct list of coverages (in order corresponding to that of segments in SegmentedGenome;
    //this may not be in genomic order, depending on how the segments are sorted in the segment file,
    //so we cannot simply take the list of coverages in the order from TargetCollection.targets()
    final List<SimpleInterval> segments = segmentedGenome.getSegments();
    numSegments = segments.size();
    final List<Double> coverages = segments.stream()
            .flatMap(s -> targetCoverages.targets(s).stream())
            .map(ReadCountRecord.SingleSampleRecord::getCount)
            .collect(Collectors.toList());
    numTargets = coverages.size();
    coverageMin = Collections.min(coverages);
    coverageMax = Collections.max(coverages);
    //partition coverages with target indices by segment
    int targetIndex = 0;
    for (final SimpleInterval segment : segments) {
        final List<ReadCountRecord.SingleSampleRecord> targetCoveragesInSegment = targetCoverages.targets(segment);
        final List<IndexedCoverage> indexedCoveragesInSegment = new ArrayList<>();
        for (final ReadCountRecord.SingleSampleRecord targetCoverage : targetCoveragesInSegment) {
            final double coverage = targetCoverage.getCount();
            indexedCoveragesInSegment.add(new IndexedCoverage(coverage, targetIndex++));
        }
        indexedCoveragesPerSegment.add(indexedCoveragesInSegment);
    }
}
 
Example 11
Source File: GradientLookup.java    From regulators with Apache License 2.0 5 votes vote down vote up
private void init() {
    if (stops.isEmpty()) return;

    double minFraction = Collections.min(stops.keySet());
    double maxFraction = Collections.max(stops.keySet());

    if (Double.compare(minFraction, 0.0) > 0) { stops.put(0.0, new Stop(0.0, stops.get(minFraction).getColor())); }
    if (Double.compare(maxFraction, 1.0) < 0) { stops.put(1.0, new Stop(1.0, stops.get(maxFraction).getColor())); }
}
 
Example 12
Source File: CameraGLView.java    From AudioVideoRecordingSample with Apache License 2.0 5 votes vote down vote up
private static Camera.Size getClosestSupportedSize(List<Camera.Size> supportedSizes, final int requestedWidth, final int requestedHeight) {
	return (Camera.Size)Collections.min(supportedSizes, new Comparator<Camera.Size>() {

		private int diff(final Camera.Size size) {
			return Math.abs(requestedWidth - size.width) + Math.abs(requestedHeight - size.height);
		}

		@Override
		public int compare(final Camera.Size lhs, final Camera.Size rhs) {
			return diff(lhs) - diff(rhs);
		}
	});

}
 
Example 13
Source File: NumberInRangeGenerator.java    From jfixture with MIT License 5 votes vote down vote up
private void createRange() {
    List<Long> remaining = getRemainingValues();
    if (remaining.size() > 0 && this.numbers.size() > 0) {
        this.lower = this.upper;
        this.upper = Collections.min(remaining) + 1;
    } else {
        this.lower = limits[0];
        this.upper = limits[1];
    }

    this.numbers.clear();
}
 
Example 14
Source File: CameraThread.java    From CameraRecorder-android with MIT License 5 votes vote down vote up
private static Size getClosestSupportedSize(List<Size> supportedSizes, final int requestedWidth, final int requestedHeight) {
    return Collections.min(supportedSizes, new Comparator<Size>() {

        private int diff(final Size size) {
            return Math.abs(requestedWidth - size.getWidth()) + Math.abs(requestedHeight - size.getHeight());
        }

        @Override
        public int compare(final Size lhs, final Size rhs) {
            return diff(lhs) - diff(rhs);
        }
    });

}
 
Example 15
Source File: CollectionUtil.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 返回无序集合中的最小值,使用元素默认排序
 */
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {
	return Collections.min(coll);
}
 
Example 16
Source File: DispatchLocationService.java    From openlocate-android with MIT License 4 votes vote down vote up
public static boolean sendLocations(Context context, List<OpenLocate.Endpoint> endpoints) {

        boolean isSuccess = true;

        SQLiteOpenHelper helper = DatabaseHelper.getInstance(context);
        LocationDataSource dataSource = new LocationDatabase(helper);
        HttpClient httpClient = new HttpClientImpl();

        LocationDispatcher dispatcher = new LocationDispatcher();
        String userAgent = getUserAgent(context);
        List<Long> timestamps = new ArrayList<>(endpoints.size());
        for (OpenLocate.Endpoint endpoint : endpoints) {

            String key = md5(endpoint.getUrl().toLowerCase());

            try {
                long timestamp = SharedPreferenceUtils.getInstance(context).getLongValue(key, 0);
                List<OpenLocateLocation> sentLocations = dispatcher.postLocations(httpClient, endpoint, userAgent, timestamp, dataSource);

                if (sentLocations != null && sentLocations.isEmpty() == false) {
                    long latestCreatedLocationDate =
                            sentLocations.get(sentLocations.size() - 1).getCreated().getTime();
                    SharedPreferenceUtils.getInstance(context).setValue(key, latestCreatedLocationDate);
                } else if (sentLocations != null && sentLocations.isEmpty()) {
                    isSuccess = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            timestamps.add(SharedPreferenceUtils.getInstance(context).getLongValue(key, 0));
        }

        Long min = Collections.min(timestamps);
        if (min != null) {
            long expired = System.currentTimeMillis() - EXPIRED_PERIOD;

            if (min < expired) {
                min = expired;
            }

            try {
                dataSource.deleteBefore(min);
            } catch (SQLiteFullException exception) {
                Log.w(TAG, "Database is full. Cannot purge data.");
            } finally {
                dataSource.close();
            }
        }

        return isSuccess;
    }
 
Example 17
Source File: Stats.java    From january with Eclipse Public License 1.0 4 votes vote down vote up
static double[] outlierValuesList(final Dataset a, final IndexIterator it, int nl, int nh) {
	final List<Double> lList = new ArrayList<Double>(nl);
	final List<Double> hList = new ArrayList<Double>(nh);

	double lx = Double.POSITIVE_INFINITY;
	double hx = Double.NEGATIVE_INFINITY;

	while (it.hasNext()) {
		double x = a.getElementDoubleAbs(it.index);
		if (Double.isNaN(x)) {
			continue;
		}
		if (x < lx) {
			if (lList.size() == nl) {
				lList.remove(lx);
			}
			lList.add(x);
			lx = Collections.max(lList);
		} else if (x == lx) {
			if (lList.size() < nl) {
				lList.add(x);
			}
		}

		if (x > hx) {
			if (hList.size() == nh) {
				hList.remove(hx);
			}
			hList.add(x);
			hx = Collections.min(hList);
		} else if (x == hx) {
			if (hList.size() < nh) {
				hList.add(x);
			}
		}
	}

	nl = lList.size();
	nh = hList.size();

	// Attempt to make values distinct
	if (lx >= hx) {
		Collections.sort(hList);
		for (double h : hList) {
			if (h > hx) {
				hx = h;
				break;
			}
			nh--;
		}
		if (lx >= hx) {
			Collections.sort(lList);
			Collections.reverse(lList);
			for (double l : lList) {
				if (l < lx) {
					lx = l;
					break;
				}
				nl--;
			}
		}
	}
	return new double[] {lx, hx, nl, nh};
}
 
Example 18
Source File: ExecutionSemester.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static ExecutionSemester readFirstExecutionSemester() {
    final Set<ExecutionSemester> exeutionPeriods = Bennu.getInstance().getExecutionPeriodsSet();
    return exeutionPeriods.isEmpty() ? null : Collections.min(exeutionPeriods);
}
 
Example 19
Source File: InterProceduralControlFlowDistanceCalculator.java    From botsing with Apache License 2.0 4 votes vote down vote up
protected static ControlFlowDistance getControlDependenceDistancesFor(ExecutionResult result, MethodCall call, BytecodeInstruction instruction, String className, String methodName, Set<Branch> handled) {
    Set<ControlFlowDistance> cdDistances = getDistancesForControlDependentBranchesOf(result, call, instruction, className, methodName, handled);
        return Collections.min(cdDistances);
}
 
Example 20
Source File: MemEvaluationStatistics.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public double getCardinality(StatementPattern sp) {

	Value subj = getConstantValue(sp.getSubjectVar());
	if (!(subj instanceof Resource)) {
		// can happen when a previous optimizer has inlined a comparison
		// operator.
		// this can cause, for example, the subject variable to be
		// equated to a literal value.
		// See SES-970 / SES-998
		subj = null;
	}
	Value pred = getConstantValue(sp.getPredicateVar());
	if (!(pred instanceof IRI)) {
		// can happen when a previous optimizer has inlined a comparison
		// operator. See SES-970 / SES-998
		pred = null;
	}
	Value obj = getConstantValue(sp.getObjectVar());
	Value context = getConstantValue(sp.getContextVar());
	if (!(context instanceof Resource)) {
		// can happen when a previous optimizer has inlined a comparison
		// operator. See SES-970 / SES-998
		context = null;
	}

	// Perform look-ups for value-equivalents of the specified values
	MemResource memSubj = valueFactory.getMemResource((Resource) subj);
	MemIRI memPred = valueFactory.getMemURI((IRI) pred);
	MemValue memObj = valueFactory.getMemValue(obj);
	MemResource memContext = valueFactory.getMemResource((Resource) context);

	if (subj != null && memSubj == null || pred != null && memPred == null || obj != null && memObj == null
			|| context != null && memContext == null) {
		// non-existent subject, predicate, object or context
		return 0.0;
	}

	// Search for the smallest list that can be used by the iterator
	List<Integer> listSizes = new ArrayList<>(4);
	if (memSubj != null) {
		listSizes.add(memSubj.getSubjectStatementCount());
	}
	if (memPred != null) {
		listSizes.add(memPred.getPredicateStatementCount());
	}
	if (memObj != null) {
		listSizes.add(memObj.getObjectStatementCount());
	}
	if (memContext != null) {
		listSizes.add(memContext.getContextStatementCount());
	}

	double cardinality;

	if (listSizes.isEmpty()) {
		// all wildcards
		cardinality = memStatementList.size();
	} else {
		cardinality = (double) Collections.min(listSizes);

		// List<Var> vars = getVariables(sp);
		// int constantVarCount = countConstantVars(vars);
		//
		// // Subtract 1 from var count as this was used for the list
		// size
		// double unboundVarFactor = (double)(vars.size() -
		// constantVarCount) / (vars.size() - 1);
		//
		// cardinality = Math.pow(cardinality, unboundVarFactor);
	}

	return cardinality;
}