如何在Collectors.toMap合并函数中获取密钥? [英] How to get the key in Collectors.toMap merge function?
问题描述
在 Collectors.toMap()
期间找到重复的键条目时,合并函数(o1,o2)
被叫。
When a duplicate key entry is found during Collectors.toMap()
, the merge function (o1, o2)
is called.
问题:如何获得导致重复的密钥?
Question: how can I get the key that caused the duplication?
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));
在合并功能中,我想根据键决定我取消映射,或继续并接受这些值。
Inside the merge function I want to decide based on the key which if I cancel the mapping, or continue and take on of those values.
推荐答案
您需要使用自定义收集器或使用不同的方法。
You need to use a custom collector or use a different approach.
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中,这就是为什么我很确定没有使用的内置函数。 ;)
Writing a custom collector is rather more complicated. You need a TriConsumer (key and two values) is similar which is not in the JDK which is why I am pretty sure there is no built in function which uses. ;)
这篇关于如何在Collectors.toMap合并函数中获取密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!