两个代码段之间的区别

时间:2018-06-13 11:49:32

标签: java-8 java-stream collectors

我已经编写了一个示例lambda代码,现在我想了解一个声明。

我的示例代码: -

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

当我使用

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

它工作正常,但是当我使用

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

我收到以下错误

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)

这两个陈述有什么区别

1 个答案:

答案 0 :(得分:3)

第一个示例代码段使用toMap收集器的重载:

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

使用mergeFunction函数来解决密钥冲突,因此不会抛出异常,而第二个示例代码段使用toMap收集器的此重载:

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

如果存在密钥冲突,则会抛出异常,因为地图不能有重复的密钥。