Search code examples
javalambdajava-stream

How do I find the largest number from a list and its occurrences using lambdas?


Please find below a code that counts the number of occurrences of numbers in a stream and returns a map with the number as the key and the value as its occurrences across the stream:

Map<Integer, Long> collect = Stream.of(1, 2, 3, 4, 4, 55555, 12)
                .collect(groupingBy(Function.identity(), counting()));

How do I limit the resulting map to only the biggest number (or numbers in case of a tie)?


Solution

  • Take a look at this simple example:

    public static void getMeNumbersWithHighestFrequence3(int[] numbers, int howMany) {
    
        Map<Integer, Long> collect = IntStream.of(numbers).boxed().collect(groupingBy(Function.identity(), TreeMap::new, counting())).descendingMap().entrySet().stream()
                .limit(howMany)
                .collect(TreeMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()), Map::putAll);
    
    }
    

    You could also somehow search for them by putting a filter value and it will take all entries with key values greater than that value, something like:

      public static void getMeNumbersWithHighestFrequenceByFilterNumber(int[] numbers, int value) {
    
            Map<Integer, Long> collect = IntStream.of(numbers).boxed().collect(groupingBy(Function.identity(), TreeMap::new, counting())).descendingMap().headMap(value, true);
    
        }
    

    Simple usage:


    public static void main(String[] args) {
            int[] numbers = {1, 2, 3, 4, 4, 55555, 12};
            getMeNumbersWithHighestFrequence(numbers, 5);
        }