3

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

 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)));

但它给了我以下错误。

方法 java.util.stream.Collectors.toMap(java.util.function.Function,java.util.function.Function,java.util.function.BinaryOperator) 不适用(推理变量 U 具有不兼容的边界相等约束:java.util.function.Function) util.List 下界:java.lang.Boolean,java.util.List)

有人可以解释编译器错误以及如何解决这个问题。提前致谢

4

2 回答 2

4

看看javadoc。这是因为List#addAllproducer boolean,它不能用作下游功能。您可以使用流:

Stream.concat(index1.stream(), index2.stream())
                         .collect(Collectors.toList())

或使用 apache commons 集合:

ListUtils.union(index1, index2)
于 2019-11-02T08:00:23.957 回答
0

如果您想遵循您的代码,或者像这样:

 (index1, index2) -> {
                        index1.addAll(index2);
                        return index1;
                    }

完整版:

 Map<String, List<Integer>> sortedStringToIndex = IntStream.range(0, strs.length)
            .mapToObj(i -> new AbstractMap.SimpleEntry<>(sortString(strs[i]), i))
            .collect(Collectors.toMap(
                              AbstractMap.SimpleEntry::getKey,
                              pair -> new ArrayList<>(Collections.singletonList(pair.getValue())),
                              (l1, l2) -> {l1.addAll(l2);return l1; }
                           )
                   );
于 2019-11-02T08:10:32.527 回答