Java Code Examples for java.util.Comparator#comparingInt()

The following examples show how to use java.util.Comparator#comparingInt() . 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: Solution4.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public int findKthLargest(int[] nums, int k) {
    int len = nums.length;
    // 使用一个含有 k 个元素的最小堆
    PriorityQueue<Integer> minHeap = new PriorityQueue<>(k, Comparator.comparingInt(a -> a));
    for (int i = 0; i < k; i++) {
        minHeap.offer(nums[i]);
    }
    for (int i = k; i < len; i++) {
        // 看一眼,不拿出,因为有可能没有必要替换
        Integer topElement = minHeap.peek();
        // 只要当前遍历的元素比堆顶元素大,堆顶弹出,遍历的元素进去
        if (nums[i] > topElement) {
            // Java 没有 replace,所以得先 poll 出来,然后再放回去
            minHeap.poll();
            minHeap.offer(nums[i]);
        }
    }
    return minHeap.peek();
}
 
Example 2
Source File: SortableASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private List<PropertyNode> findProperties(AnnotationNode annotation, final ClassNode classNode, final List<String> includes,
                                          final List<String> excludes, final boolean allProperties,
                                          final boolean includeSuperProperties, final boolean allNames) {
    Set<String> names = new HashSet<String>();
    List<PropertyNode> props = getAllProperties(names, classNode, classNode, true, false, allProperties,
            false, includeSuperProperties, false, false, allNames, false);
    List<PropertyNode> properties = new ArrayList<PropertyNode>();
    for (PropertyNode property : props) {
        String propertyName = property.getName();
        if ((excludes != null && excludes.contains(propertyName)) ||
                includes != null && !includes.contains(propertyName)) continue;
        properties.add(property);
    }
    for (PropertyNode pNode : properties) {
        checkComparable(pNode);
    }
    if (includes != null) {
        Comparator<PropertyNode> includeComparator = Comparator.comparingInt(o -> includes.indexOf(o.getName()));
        properties.sort(includeComparator);
    }
    return properties;
}
 
Example 3
Source File: BasicTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void testMaxBy() {
    Comparator<People> cmp = Comparator.comparing(People::getFirstName);
    // lesser
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[1]);
    // euqal
    cmp = Comparator.comparing(People::getLastName);
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]);
    // greater
    cmp = Comparator.comparingInt(People::getAge);
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]);
}
 
Example 4
Source File: Util.java    From robozonky with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param ratingsInOrderOfPreference Iteration order from more demanded to less.
 * @return
 */
static Comparator<Rating> getRatingByDemandComparator(final Set<Rating> ratingsInOrderOfPreference) {
    Map<Rating, Integer> ratingRanking = new EnumMap<>(Rating.class);
    AtomicInteger rank = new AtomicInteger();
    ratingsInOrderOfPreference.forEach(r -> ratingRanking.computeIfAbsent(r, key -> rank.getAndIncrement()));
    return Comparator.comparingInt(o -> ratingRanking.getOrDefault(o, Integer.MAX_VALUE));
}
 
Example 5
Source File: Solution.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public List<Integer> topKFrequent(int[] nums, int k) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        if (map.containsKey(nums[i])) {
            map.put(nums[i], map.get(nums[i]) + 1);
        } else {
            map.put(nums[i], 1);
        }
    }

    // 这里应该组件一个最小堆,Comparator.comparingInt(Map.Entry::getValue) 这个语法是 IDEA 工具帮我完成的
    Queue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getValue));
    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
        if (queue.size() == k) {
            if (entry.getValue() > queue.peek().getValue()) {
                queue.remove();
                queue.add(entry);
            }
        } else {
            queue.add(entry);
        }
    }

    Integer[] temp = new Integer[k];
    for (int i = k - 1; i >= 0; i--) {
        temp[i] = queue.poll().getKey();
    }
    List<Integer> result = new ArrayList<>(k);
    for (int i = 0; i < k; i++) {
        result.add(temp[i]);
    }
    return result;
}
 
Example 6
Source File: Solution9.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public int findKthLargest(int[] nums, int k) {
    int len = nums.length;
    if (len == 0 || k > len) {
        throw new IllegalArgumentException("参数错误");
    }
    // 使用一个含有 len 个元素的最小堆
    PriorityQueue<Integer> minHeap = new PriorityQueue<>(len, Comparator.comparingInt(a -> a));
    for (int i = 0; i < len; i++) {
        minHeap.add(nums[i]);
    }
    for (int i = 0; i < len - k; i++) {
        minHeap.poll();
    }
    return minHeap.peek();
}
 
Example 7
Source File: BoundedElasticScheduler.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
BoundedServices(BoundedElasticScheduler parent) {
	this.parent = parent;
	this.clock = parent.clock;
	this.busyQueue = new PriorityBlockingQueue<>(parent.maxThreads,
			Comparator.comparingInt(bs -> bs.markCount));
	this.idleQueue = new ConcurrentLinkedDeque<>();
}
 
Example 8
Source File: MedianOfNSortedArrays.java    From LeetCode-Sol-Res with MIT License 5 votes vote down vote up
/**
 * Heap. Merge.
 * Just like how we merge 2 sorted arrays, we can do the same to N arrays.
 * The only difference is that a min-heap is needed to find the next minimum.
 * Note that the median depends on whether we have odd or even total numbers, N.
 * If N is odd, median is the number at N / 2 + 1.
 * E.g. N = 7, N/2 = 3, the 4th number is the median.
 * If N is even, median is the average of N / 2 and N / 2 + 1.
 * E.g. N = 8, N/2 = 4, the average of 4th and 5th is the median.
 */
public double getMedian(int[][] arrs) {
    if (arrs.length == 0) return 0;
    // int[] is {row, column, value}
    PriorityQueue<int[]> pq = new PriorityQueue<>(arrs.length, Comparator.comparingInt(a -> a[2]));
    int n = 0; // Total number of integers.
    for (int i = 0; i < arrs.length; i++) {
        pq.offer(new int[]{i, 0, arrs[i][0]});
        n += arrs[i].length;
    }

    double median = 0;
    for (int i = 0; i < n / 2; i++) { // Loop n / 2 times.
        // Get min from heap, then add its next to heap if there is one.
        int[] min = pq.poll();
        if (min[1] < arrs[min[0]].length - 1) {
            min[1]++;
            min[2] = arrs[min[0]][min[1]];
            pq.offer(min);
        }
        if (i == n / 2 - 2 && n % 2 == 0) { // When n is even, record the last 2 values.
            median = min[2];
        } else if (i == n / 2 - 1 && n % 2 == 0) {
            median = (median + min[2]) / 2;
        } else if (i == n / 2 - 1 && n % 2 == 1) { // When n is odd, poll one more value at the last iteration.
            median = pq.poll()[2];
        }
    }
    return median;
}
 
Example 9
Source File: SageHotspotAnnotation.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
private static VariantContext primary(@NotNull final VariantContext hotspot, @NotNull final List<VariantContext> overlaps) {
    Comparator<VariantContext> comparator = Comparator.comparingInt(o -> o.getEnd() - o.getStart());
    final List<VariantContext> all = Lists.newArrayList(overlaps);
    all.add(hotspot);
    all.sort(comparator.reversed());

    return all.get(0);
}
 
Example 10
Source File: BasicTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void testMaxBy() {
    Comparator<People> cmp = Comparator.comparing(People::getFirstName);
    // lesser
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[1]);
    // euqal
    cmp = Comparator.comparing(People::getLastName);
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]);
    // greater
    cmp = Comparator.comparingInt(People::getAge);
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]);
}
 
Example 11
Source File: BasicTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testMaxBy() {
    Comparator<People> cmp = Comparator.comparing(People::getFirstName);
    // lesser
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[1]);
    // euqal
    cmp = Comparator.comparing(People::getLastName);
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]);
    // greater
    cmp = Comparator.comparingInt(People::getAge);
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]);
}
 
Example 12
Source File: EuropeanAIPlayer.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets the best plan for a colony from the tipMap.
 *
 * @param colony The {@code Colony} to check.
 * @return The tile with the best plan for a colony, or null if none found.
 */
public Tile getBestPlanTile(Colony colony) {
    final Comparator<TileImprovementPlan> valueComp
        = Comparator.comparingInt(TileImprovementPlan::getValue);
    final Function<Tile, TileImprovementPlan> tileMapper = t ->
        tipMap.get(t);
    TileImprovementPlan best
        = maximize(map(colony.getOwnedTiles(), tileMapper),
                   isNotNull(), valueComp);
    return (best == null) ? null : best.getTarget();
}
 
Example 13
Source File: Tile.java    From freecol with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the best food type to produce here.
 *
 * @return The {@code AbstractGoods} to produce.
 */
public AbstractGoods getBestFoodProduction() {
    final Comparator<AbstractGoods> goodsComp
        = Comparator.comparingInt(ag ->
            getPotentialProduction(ag.getType(), null));
    return maximize(flatten(getType().getAvailableProductionTypes(true),
                            ProductionType::getOutputs),
                    AbstractGoods::isFoodType, goodsComp);
}
 
Example 14
Source File: BasicTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testMaxBy() {
    Comparator<People> cmp = Comparator.comparing(People::getFirstName);
    // lesser
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[1]);
    // euqal
    cmp = Comparator.comparing(People::getLastName);
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]);
    // greater
    cmp = Comparator.comparingInt(People::getAge);
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]);
}
 
Example 15
Source File: BasicTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void testMaxBy() {
    Comparator<People> cmp = Comparator.comparing(People::getFirstName);
    // lesser
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[1]);
    // euqal
    cmp = Comparator.comparing(People::getLastName);
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]);
    // greater
    cmp = Comparator.comparingInt(People::getAge);
    assertSame(maxBy(cmp).apply(people[0], people[1]), people[0]);
}
 
Example 16
Source File: MemoryUsageTreeViewer.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected ITmfTreeColumnDataProvider getColumnDataProvider() {
    return () -> {
        Comparator<TmfGenericTreeEntry<MemoryUsageTreeModel>> compareTid = Comparator.comparingInt(c -> c.getModel().getTid());
        return ImmutableList.of(
                createColumn(Messages.MemoryUsageTree_ColumnProcess, Comparator.comparing(TmfGenericTreeEntry::getName)),
                createColumn(Messages.MemoryUsageTree_ColumnTID, compareTid),
                new TmfTreeColumnData(Messages.MemoryUsageTree_Legend));
    };
}
 
Example 17
Source File: TextScan.java    From fdb-record-layer with Apache License 2.0 4 votes vote down vote up
@Nullable
private static Boolean entriesContainAllWithin(@Nonnull List<IndexEntry> entries, int maxDistance) {
    if (entries.isEmpty()) {
        return null;
    }
    List<List<Integer>> positionLists = getPositionsLists(entries);
    if (positionLists.stream().anyMatch(List::isEmpty)) {
        // Remove any empty lists. They indicate that the token is so prevalent
        // that the position list information is not retained.
        positionLists = positionLists.stream().filter(list -> !list.isEmpty()).collect(Collectors.toList());
        if (positionLists.isEmpty()) {
            // If they are all empty, then we assume that they were all close.
            return Boolean.TRUE;
        }
    }

    PriorityQueue<Pair<Integer, Iterator<Integer>>> minQueue = new PriorityQueue<>(positionLists.size(), Comparator.comparingInt(Pair::getLeft));
    int max = Integer.MIN_VALUE;
    for (List<Integer> positionList : positionLists) {
        Iterator<Integer> positionIterator = positionList.iterator();
        int value = positionIterator.next();
        max = Math.max(max, value);
        minQueue.add(Pair.of(value, positionIterator));
    }

    while (true) {
        // Pop the smallest position off of the queue and check to see
        // if it is within maxDistance of the current largest value.
        Pair<Integer, Iterator<Integer>> minElem = minQueue.poll();
        int min = minElem.getLeft();
        if (max - min <= maxDistance) {
            // Current span is within maximum allowed. Return true.
            return Boolean.TRUE;
        }
        Iterator<Integer> minIterator = minElem.getRight();
        if (minIterator.hasNext()) {
            // Advance this iterator and place it back in the queue with the
            // new associated value.
            int nextValue = minIterator.next();
            max = Math.max(max, nextValue);
            minQueue.add(Pair.of(nextValue, minIterator));
        } else {
            // Exhausted one of the position lists. We didn't find a span that
            // was less than or equal to the maximum allowed span.
            break;
        }
    }
    return Boolean.FALSE;
}
 
Example 18
Source File: ComparatorTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testComparingInt() {
    Comparator<Item> comparator = Comparator.comparingInt(Item::getOrderAsInt);
    checkComparison(comparator, orderedItems);
}
 
Example 19
Source File: FieldDefinition.java    From cron-utils with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a field definition comparator. Will compare by CronFieldName order value;
 *
 * @return Comparator for FieldDefinition instance, never null;
 */
public static Comparator<FieldDefinition> createFieldDefinitionComparator() {
    return Comparator.comparingInt(o -> o.getFieldName().getOrder());
}
 
Example 20
Source File: CronParserField.java    From cron-utils with Apache License 2.0 2 votes vote down vote up
/**
 * Create a Comparator that compares CronField instances using CronFieldName value.
 *
 * @return Comparator for CronField instance, never null.
 */
public static Comparator<CronParserField> createFieldTypeComparator() {
    return Comparator.comparingInt(o -> o.getField().getOrder());
}