gpt4 book ai didi

java - 如何使用 Collectors.toMap 获取 Map

转载 作者:搜寻专家 更新时间:2023-11-01 02:37:42 26 4
gpt4 key购买 nike

我有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));

第一个参数是一个 Function,它映射了映射中的 Key

第二个是 Function,它映射 map 中的 Value。由于您需要对它们进行计数,因此它将始终返回 1。

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

关于java - 如何使用 Collectors.toMap 获取 Map<Integer,Integer>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43211149/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com