Why does Collectors.toMap report value instead of key on Duplicate Key error?

后端 未结 5 1697
春和景丽
春和景丽 2020-11-30 13:31

This is really a question about a minor detail, but I\'m under the impression to get something wrong here. If you add duplicate keys using Collectors.toMap-method it throws

5条回答
  •  醉梦人生
    2020-11-30 14:32

    In Java 8, duplicate values from two streams (or with same strems iterating twice) are not allowed to be merged into the Map at a time. You can use Collectors.groupingBy & Collectors.mapping to combine the results into the Map> or Map> for processing.

        List employees = new ArrayList<>();
        employees.add(new Employee("Sachin", 40));
        employees.add(new Employee("Sachin", 30));   
        employees.add(new Employee("Rahul", 30));
    
        Map> map = employees.stream()
                                        .collect(
                                                Collectors.groupingBy(
                                                                    Employee::getAge, 
                                                                    Collectors.mapping(
                                                                            Employee::getName,
                                                                            Collectors.toSet()
                                                                    )
                                                                )
                                                );
    

提交回复
热议问题