⬆️ ⬇️

7 ways to use groupingBy in Stream API

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





The class of the worker, on which we will experiment
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; } } 


1. Grouping the list of workers according to their positions (division into lists)



  Map<String, List<Worker>> map1 = workers.stream() .collect(Collectors.groupingBy(Worker::getPosition)); 


2. Grouping the list of workers according to their positions (division into sets)



 Map<String, Set<Worker>> map2 = workers.stream() .collect(Collectors.groupingBy(Worker::getPosition, Collectors.toSet())); 


3. Counting the number of workers in a particular position



 Map<String, Long> map3 = workers.stream() .collect(Collectors.groupingBy(Worker::getPosition, Collectors.counting())); 


4. Grouping the list of workers by their positions, while we are only interested in names



 Map<String, Set<String>> map4 = workers.stream() .collect(Collectors.groupingBy(Worker::getPosition, Collectors.mapping(Worker::getName, Collectors.toSet()))); 


5. The calculation of the average salary for the position



 Map<String, Double> map5 = workers.stream() .collect(Collectors.groupingBy(Worker::getPosition, Collectors.averagingInt(Worker::getSalary))); 


6. Grouping the list of workers by their positions, workers are represented only by names as a single line.



 Map<String, String> map6 = workers.stream() .collect(Collectors.groupingBy(Worker::getPosition, Collectors.mapping(Worker::getName, Collectors.joining(", ", "{","}"))) ); 


7. Grouping the list of workers by their positions and by age.



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/



All Articles