我正在编写一个简单的表达式,其中我必须收集 String
的 Map
与数组中的索引列表。为此,我尝试使用
Collectors.toMap(keyMapper, valueMapper, mergeFunction).
其要点如下。
Map<String, List<Integer>> sortedStringToIndex = IntStream.range(0, strs.length)
.mapToObj(i -> new AbstractMap.SimpleEntry<String,Integer>(sortString(strs[i]),i))
.collect(Collectors.toMap((Map.Entry<String,Integer> pair) -> pair.getKey(),
(Map.Entry<String,Integer> pair) -> {
List<Integer> val = new ArrayList<>(){{add(pair.getValue());}};
return val;
}, (List<Integer> index1, List<Integer> index2) -> index1.addAll(index2)));
但是它给了我以下错误。
method java.util.stream.Collectors.toMap(java.util.function.Function,java.util.function.Function,java.util.function.BinaryOperator) is not applicable (inference variable U has incompatible bounds equality constraints: java.util.List lower bounds: java.lang.Boolean,java.util.List)
有人可以解释一下编译器错误以及如何解决这个问题吗?提前致谢
最佳答案
看看javadoc 。这是因为 List#addAll
产生 boolean
,它不能用作下游函数。您可以使用流:
Stream.concat(index1.stream(), index2.stream())
.collect(Collectors.toList())
或者使用 apache commons 集合:
ListUtils.union(index1, index2)
关于java - 编译器在收集器 toMap 中给出一般错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58669253/