Reputation: 372
I have List<StudentRecord> records
containing StudentRecord
instances.
public class StudentRecord {
private String lastName;
private String firstName;
private int mark;
//constructor + getters
}
How do I make Map<Integer,Integer>
that as key has mark and as value, number of mark occurances in records list? Note: I have to use exactly this method toMap.
I have tried this myself:
Map<Integer,Integer>mapaPoOcjenama2=
records.stream()
.collect(Collectors.toMap(StudentRecord::getMark, Collectors.counting(), mergeFunction));
But I am now sure how Collectors.counting() works and dont know what to write as merge function.
Upvotes: 4
Views: 2496
Reputation: 120968
that's fairly easy to with toMap
:
collect(Collectors.toMap(StudentRecord::getMark,
s -> 1,
(left, right) -> left + right));
The first argument is a Function
that maps the Key
in the map.
The second is a Function
that maps the Value
in the map. Since you need to count them, it will always return 1.
And the third is a BiFunction
that says how to merge two keys in case they are the same. Since you want to count, you will increment by one all the time.
Upvotes: 4