java - 编译器在收集器 toMap 中给出一般错误

标签 java dictionary generics arraylist java-stream

我正在编写一个简单的表达式,其中我必须收集 StringMap 与数组中的索引列表。为此,我尝试使用

 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/

相关文章:

java - 如何在从数据库获取数据的同时创建异步任务加载后台

python - 按多个键分组并汇总/平均字典列表的多个值

c++ - 如何使用不同类型的键搜索 std::map

c# - 不允许为可为空的枚举返回 null

java - 此代码是否适用于二叉树中的欧拉之旅?

java - 为什么使用单例来包装广播变量?

java - 正常运行GWT shell,编译时使用-noserver?

python - 将具有父项的对象字典转换为具有子项的嵌套字典

java - 泛型 : Specify that parameter must be an interface

c# - 受约束泛型类型参数的逆变