How to get a <Integer, Integer> card using Collectors.toMap?

I have List<StudentRecord> recordscontaining StudentRecordinstances.

public class StudentRecord {

private String lastName;
private String firstName;
private int mark;

//constructor + getters
}

How to make Map<Integer,Integer>sure that there is a label as a key and as a value, the number of marks in the list of records? Note: I have to use this particular toMap method .

I tried this myself:  Map<Integer,Integer>mapaPoOcjenama2= records.stream() .collect(Collectors.toMap(StudentRecord::getMark, Collectors.counting(), mergeFunction));

But now I'm sure how Collectors.counting () works and does not know what to write as a merge function.

+4
source share
1 answer

which is pretty easy with toMap:

collect(Collectors.toMap(StudentRecord::getMark, 
        s -> 1, 
        (left, right) -> left + right));

The first argument is the Functionone that displays Keyon the map.

- Function, Value . , 1.

- BiFunction, , , . , .

+4

Source: https://habr.com/ru/post/1674006/


All Articles