Beginners often find it hard to imagine the benefits of using the Stream API instead of regular loops,
under the cut are a few examples that will help you significantly compress your bloated code
public class Worker{ private String name; private int age; private int salary; private String position; public Worker(String name, int age, int salary, String position) { this.name = name; this.age = age; this.salary = salary; this.position = position; } public String getName() { return name; } public int getAge() { return age; } public int getSalary() { return salary; } public String getPosition() { return position; } }
Map<String, List<Worker>> map1 = workers.stream() .collect(Collectors.groupingBy(Worker::getPosition));
Map<String, Set<Worker>> map2 = workers.stream() .collect(Collectors.groupingBy(Worker::getPosition, Collectors.toSet()));
Map<String, Long> map3 = workers.stream() .collect(Collectors.groupingBy(Worker::getPosition, Collectors.counting()));
Map<String, Set<String>> map4 = workers.stream() .collect(Collectors.groupingBy(Worker::getPosition, Collectors.mapping(Worker::getName, Collectors.toSet())));
Map<String, Double> map5 = workers.stream() .collect(Collectors.groupingBy(Worker::getPosition, Collectors.averagingInt(Worker::getSalary)));
Map<String, String> map6 = workers.stream() .collect(Collectors.groupingBy(Worker::getPosition, Collectors.mapping(Worker::getName, Collectors.joining(", ", "{","}"))) );
J2ck user prompted
Map<String, Map<Integer, List<Worker>>> collect = workers.stream() .collect(Collectors.groupingBy(Worker::getPosition, Collectors.groupingBy(Worker::getAge)));
Are there any other original ideas for using groupingBy? Write them in the comments.
Source: https://habr.com/ru/post/348536/