如何使用 Collectors.toMap 获取 Map<Integer,Integer>?

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

我有 List<StudentRecord> records 个包含 StudentRecord 个实例。

public class StudentRecord {

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

//constructor + getters
}

如何使 Map<Integer,Integer> 键有标记,值有标记在记录列表中出现的次数?注意:我必须完全使用这种方法 toMap.

我自己试过: Map<Integer,Integer>mapaPoOcjenama2= records.stream() .collect(Collectors.toMap(StudentRecord::getMark, Collectors.counting(), mergeFunction));

但我现在确定 Collectors.counting() 是如何工作的,不知道要写什么作为合并函数。

使用 toMap:

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

第一个参数是映射 KeyFunction

第二个是映射 ValueFunction。由于你需要计算它们,它总是 return 1.

第三个是 BiFunction,说明如何合并两个键,以防它们相同。既然要数,就一直加一