Search code examples
java-8java-streamcollectors

Difference between two code snippets


I have written a sample lambda code, now I want to get some idea about a statement.

My sample code:-

public static void main( String[] args )
{
    List<ItemObject> record = new ArrayList();
    ItemObject object1 = new ItemObject();
    ItemObject object2 = new ItemObject();
    ItemObject object3 = new ItemObject();
    ItemObject object4 = new ItemObject();
    record.add(object1);
    record.add(object2);
    record.add(object3);
    record.add(object4);

    Map<String, ItemObject> stbProcessingMap = new HashMap();
    stbProcessingMap = record.stream().collect(Collectors.toMap(recordingItem -> "key", recordingItem -> recordingItem, (r1,r2) -> r2));
    System.out.println(stbProcessingMap);
}

when I use

stbProcessingMap = record.stream().collect(Collectors.toMap(recordingItem -> "key", recordingItem -> recordingItem, (r1,r2) -> r2));

Its working fine but when I use

stbProcessingMap = record.stream().collect(Collectors.toMap(recordingItem -> "key", recordingItem -> recordingItem));

I am getting following error

Exception in thread "main" java.lang.IllegalStateException: Duplicate key com.modle.ItemObject@7cca494b
at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
at java.util.HashMap.merge(HashMap.java:1245)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
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 com.sample.App.main(App.java:30)

what is the difference between those two statements


Solution

  • The first example snippet uses this overload of the toMap collector:

    toMap(Function<? super T,? extends K> keyMapper,
                   Function<? super T,? extends U> valueMapper,
                   BinaryOperator<U> mergeFunction)
    

    which uses a mergeFunction function to resolve key collisions hence the exception will not the thrown whereas the second example snippet uses this overload of the toMap collector:

    toMap​(Function<? super T,? extends K> keyMapper,
                  Function<? super T,? extends U> valueMapper)
    

    which will throw an exception if there is a key collision as a map cannot have duplicate keys.