异常标识:java.lang.IllegalStateException: Duplicate key 1;
代码如下:
Map<String,RuleNode> allMap=treeList.stream().collect(Collectors.toMap(RuleNode::getId, Function.identity());
错误原因:原因是存在重复key导致。
查看toMap文档: public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper) Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements. If the mapped keys contains duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection operation is performed. If the mapped keys may have duplicates, use toMap(Function, Function, BinaryOperator) instead. API Note: It is common for either the key or the value to be the input elements. In this case, the utility method Function.identity() may be helpful. For example, the following produces a Map mapping students to their grade point average: Map<Student, Double> studentToGPA students.stream() .collect(toMap(Functions.identity(), student -> computeGPA(student))); 1 2 And the following produces a Map mapping a unique identifier to students: Map<String, Student> studentIdToStudent students.stream().collect(toMap(Student::getId, Functions.identity());
如果在最后生成map的时候,mapped到的keys中如果包含重复的键(通过key类型的equals方法来判断),则会抛出异常IllegalStateException。但是,后面也提到,如果keys中包含有相同的键,则可以使用toMap(Function, Function, BinaryOperator)方法来替代。
改进代码:
Map<String,RuleNode> allMap=treeList.stream().collect(Collectors.toMap(RuleNode::getId, Function.identity(),(entity1,entity2) -> entity1));
也就是有重复值的时候,我取先进来的值,也就是e1。