I was writing one simple expression wherein I have to collect Map
of String
vs the list of indexes from an array. To do that I am trying to use
Collectors.toMap(keyMapper, valueMapper, mergeFunction).
Gist of it is as follow.
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)));
But It gives me following error.
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)
Can someone please explain the compiler error and how to fix this. Thanks in advance
Take a look at javadoc. It's because List#addAll
produces boolean
, it cannot be used as downstream function. You can use streams:
Stream.concat(index1.stream(), index2.stream())
.collect(Collectors.toList())
Or using apache commons collections:
ListUtils.union(index1, index2)