当发现重复的按键输入时Collectors.toMap()
,合并函数(o1, o2)
叫做。
问题:如何获取导致重复的密钥?
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));
在合并函数中我想根据key如果我取消映射,或者继续并采用这些值。
您需要使用自定义收集器或使用不同的方法。
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 中,这就是为什么我很确定没有内置函数可以使用。 ;)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)