当在 Collectors.toMap()
期间发现重复的键条目时,将调用合并函数 (o1, o2)
。
问题:如何获取导致重复的 key ?
String keyvalp = "test=one\ntest2=two\ntest2=three";
Pattern.compile("\n")
.splitAsStream(keyval)
.map(entry -> entry.split("="))
.collect(Collectors.toMap(
split -> split[0],
split -> split[1],
(o1, o2) -> {
//TODO how to access the key that caused the duplicate? o1 and o2 are the values only
//split[0]; //which is the key, cannot be accessed here
},
HashMap::new));
在合并函数中,我想根据键决定是取消映射,还是继续并采用这些值。
最佳答案
您需要使用自定义收集器或使用不同的方法。
Map<String, String> map = new Hashmap<>();
Pattern.compile("\n")
.splitAsStream(keyval)
.map(entry -> entry.split("="))
.forEach(arr -> map.merge(arr[0], arr[1], (o1, o2) -> /* use arr[0]));
编写自定义收集器要复杂得多。您需要一个类似的 TriConsumer(键和两个值),它不在 JDK 中,这就是为什么我很确定没有使用内置函数的原因。 ;)
关于java - 如何获取 Collectors.toMap 合并功能中的 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44407112/