x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Java 8 Collectors groupingby examples

    1) Example that shows how to group the objects by any attribute using Collectors groupingBy()

    If you have a list of objects say list of persons and you want to group them by rollNumber, you can use Collectors groupingBy() method.

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    	
    class Student {
        private int rollNumber;
        private String name;
        private int age;
    	
        Student (int rollNumber, String name, int age) {
            this.rollNumber = rollNumber;
            this.name = name;
            this.age = age;
        }
        
        // removed getters and setter for brevity    
       
        @Override
        public String toString() {
            return "Student [rollNumber=" + rollNumber + ", name=" + name + ", age="+ age + "]";
        }
    } 
    // Converts List to Map using Collectors groupingBy() method
    public class ListToMapConverter { 
    
        public static void main(String[] args) {
            // create students list
    			
            Stream<Student> studentStream = students.stream();
            Map<Integer, List<Student>> rollNumberNameMap = 
            studentStream.collect(Collectors.groupingBy(Student::getRollNumber));
            System.out.println(rollNumberNameMap); 
        }
    }	

    Output :

    {1=[Student [rollNumber=1, name=John, age=13],
     Student [rollNumber=1, name=James, age=15]],
     2=[Student [rollNumber=2, name=Mark, age=14]],
     3=[Student [rollNumber=3, name=Henry, age=13]]}	

    If you have a list of objects say list of persons and you want to group them by age or name, you can use Collectors groupingBy() method.

    package java8;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class GroupingBy {
    
        public static void main(String[] args) {
            Person harry = new Person("Harry", 34);
            Person robert = new Person("Robert", 27);
            Person hillary = new Person("Hillary", 34);
            List<Person> persons = Arrays.asList(harry, robert, hillary);
            Map<Integer, List<Person>> personsGroup 
                = persons.stream().collect(Collectors.groupingBy(Person::getAge));
            System.out.println(personsGroup);
        }
    }	
    class Person {
    
        private String name;
        private int age;
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        // removed getters and setter for brevity
    
        @Override
        public String toString() {
            return "Person [name=" + name + ", age=" + age + "]";
        }
    
    }	

    Console Output :

    {34=[Person [name=Harry, age=34], Person [name=Hillary, age=34]], 27=[Person [name=Robert, age=27]]}

    2) Collectors groupingBy() and counting() example

    If you want to count the number of persons that belong to a age group, you can use Collectors groupingBy(Function, Collector).

    package java8;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class GroupingBy {
    
        public static void main(String[] args) {
            Person harry = new Person("Harry", 34);
            Person robert = new Person("Robert", 27);
            Person hillary = new Person("Hillary", 34);
            Person james = new Person("James", 31);
            List<Person> persons = Arrays.asList(harry, robert, hillary, james);
            Map<Integer, Long> personsGroupCounting 
                = persons.stream().collect(Collectors.groupingBy(Person::getAge, Collectors.counting()));
            System.out.println(personsGroupCounting);
        }
    }	

    Console Output :

    {34=2, 27=1, 31=1}	

    3) Collectors groupingBy() and mapping() example

    If you want to group the persons by age and only want the names of the persons instead of whole Person object, you can use Collectors mapping(Function, Collector) function.

    package java8;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class GroupingBy {
    
        public static void main(String[] args) {
            // create persons list
            Map<Integer, List<String>> namesByAge 
                = persons.stream().collect(Collectors.groupingBy(Person::getAge, 
                Collectors.mapping(Person::getName, Collectors.toList())));
            System.out.println(namesByAge);
        }
    }	

    Console Output :

    {34=[Harry, Hillary], 27=[Robert], 31=[James]}	

    4) Collectors groupingBy() and summingInt() example

    Suppose you have list of students and you want to calculate the total marks of a student, you can use Collectors summingInt() function.

    package java8;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class GroupingBy {
    
        public static void main(String[] args) {
            List<Student> students = new ArrayList<>();
            students.add(new Student(1, "English", 74));
            students.add(new Student(1, "Science", 89));
            students.add(new Student(2, "English", 89));
            students.add(new Student(2, "Science", 91));
            students.add(new Student(3, "English", 69));
            students.add(new Student(3, "Science", 95));
    		
            Map<Integer, Integer> marks = students.stream().collect(Collectors.groupingBy(Student::getId,
                Collectors.summingInt(Student::getMarks)));
            System.out.println(marks);
        }
    }	
    class Student {
        private final int id;
        private final String subject;
        private final int marks;
    
        public Student(int id, String subject, int marks) {
            this.id = id;
            this.subject = subject;
            this.marks = marks;
        }
    
       // removed getters and setter for brevity
    
        @Override
        public String toString() {
            return "Student [id=" + id + ", subject=" + subject + ", marks="+ marks + "]";
        }
    
    }    
    

    Console Output :

    {1=163, 2=180, 3=164}	

    5) Collectors groupingBy() and averagingInt() example

    Suppose you have list of students and you want to calculate the average of marks for a subject, you can use Collectors averagingInt() function.

    package java8;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class GroupingBy {
    
        public static void main(String[] args) {
            List<Student> students = new ArrayList<>();
            students.add(new Student(1, "English", 74));
            students.add(new Student(1, "Science", 89));
            students.add(new Student(2, "English", 89));
            students.add(new Student(2, "Science", 91));
            students.add(new Student(3, "English", 69));
            students.add(new Student(3, "Science", 95));
    		
            Map<String, Double> average = students.stream().collect(
    				Collectors.groupingBy(Student::getSubject, Collectors.averagingInt(Student::getMarks)));
    		System.out.println(average);
        }
    }
    	

    Console Output :

    {English=77.33333333333333, Science=91.66666666666667}	



    References :

    Oracle Docs Collectors

    Oracle Docs Comparator Collectors groupingBy()

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This