Rabbitman14
Rabbitman14

Reputation: 331

Using Java stream to get map containing a key and the number of occurrences of that key from a List

I have a List<Map.Entry<Double, Boolean>> feature.

I would like to count the number of occurrences of the possible values of Boolean in the list.

The current attempt I have made is

Map<Boolean, List<Map.Entry<Double, Boolean>>> classes = 
    feature.stream().collect(Collectors.groupingBy(Map.Entry::getValue));

Instead of the Map<Boolean, List<Map.Entity<Double, Boolean> I would like a Map<Boolean, Integer> where the integer is the number of occurances.

I have tried

Map<Boolean, List<Map.Entry<Double, Boolean>>> classes = 
    feature.stream().collect(Collectors.groupingBy(Map.Entry::getValue, List::size));

But this throws a no suitable method function.

I am new to the stream API so any help achieving this would be greatly appreciated!

Upvotes: 1

Views: 131

Answers (3)

Robin Topper
Robin Topper

Reputation: 2345

The other answers work perfectly, but if you insist on getting a Map<Boolean,Integer> you need this:

Map<Boolean,Integer> result = feature.stream()
            .map(Map.Entry::getValue)
            .collect(Collectors.groupingBy(
                Function.identity(), 
                Collectors.collectingAndThen(Collectors.counting(), Long::intValue)));

Upvotes: 1

Robby Cornelissen
Robby Cornelissen

Reputation: 97140

This will give you a result of Map<Boolean, Long>:

List<Map.Entry<Double, Boolean>> feature = new ArrayList<>();
Map<Boolean, Long> result = feature
        .stream()
        .map(Map.Entry::getValue)
        .collect(Collectors.groupingBy(Function.identity(),
                 Collectors.counting()));

Upvotes: 1

Ruslan K.
Ruslan K.

Reputation: 142

You can use map function to get list of Booleans and groupingBy it:

Map<Boolean, Long> collect = feature.stream()
                .map(Map.Entry::getValue)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Upvotes: 1

Related Questions