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