当在期间找到重复的键条目时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));
Run Code Online (Sandbox Code Playgroud)
在合并函数内部,我想根据键来决定,如果我取消映射,或继续并接受这些值.
我正在实现使用合并功能的自己的收集器.不幸的是,对于我的一些情况,我不能重用抛出IllegalStateException的以下JDK合并函数.
java.util.stream.Collectors#throwingMerger
Run Code Online (Sandbox Code Playgroud)
它发生的原因是它具有私有访问修饰符,并且来自其他(非内部)类的访问受到限制.但是,javadoc说:
这可以用于强制假设所收集的元素是不同的
但是,正如我所见,java doc已经过时了.它不能使用.问题是JDK是否为java开发人员提供类似功能(类似方法,常量等),或者应该自己编写?