Java Stream Map elements in a list to a number

Sparker0i :

I have a int[] converted to a List<Integer>. The task at hand is to map each element of the set to 0. So I think of converting this List to a Set and then map to 0. So for a set 1, 3, 7, 4, 8, it should look like: (1, 0), (3, 0), (7, 0), (4, 0), (8, 0). To achieve this, I've tried:

Map<Integer, Integer> map = Arrays.stream(elements)
    .boxed()
    .collect(Collectors.toMap(x -> x, x -> 0));

But while trying this, I get this error:

Exception in thread "main" java.lang.IllegalStateException: Duplicate key 0
    at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
    at java.util.HashMap.merge(HashMap.java:1254)
    at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
    at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
    at java.util.stream.IntPipeline$4$1.accept(IntPipeline.java:250)
    at java.util.Spliterators$IntArraySpliterator.forEachRemaining(Spliterators.java:1032)
    at java.util.Spliterator$OfInt.forEachRemaining(Spliterator.java:693)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
    at DeleteElementsByOccurence.main(DeleteElementsByOccurence.java:18)                  <-- Refers to the Collectors.toMap line

I know this stuff is super easy in Scala, but I am unable to figure out the logic to do in Java.

Sweeper :

elements seem to contain duplicates. To deal with this, you can supply a third argument to toMap to say what you want to do when there are duplicates. (this overload)

.collect(Collectors.toMap(x -> x, x -> 0, (x, y) -> x));

x and y are the values corresponding to two duplicate keys, and you get to decide what the new value is for that key. Since in this case all the values are 0, there's not much of a choice, is there?

You don't actually need to convert the array to a set first, because the third argument (merger function) handles duplicates automatically.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=20846&siteId=1