beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java 8 – Stream Collectors Class with examples

By Chaitanya Singh | Filed Under: Java 8 Features

Collectors is a final class that extends the Object class. In this tutorial we will see the examples of Java Stream collectors class using lambda expressions, Java Streams and other new features of Java 8.

java.lang.Object
   |
   |___java.util.stream.Collectors

Java – Stream Collectors groupingBy and counting Example

In this example, we are grouping the elements of a list using groupingBy() method of Collectors class and printing the occurrences of each element in the list.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Example {

   public static void main(String[] args) {

      List<String> names =
          Arrays.asList("Jon", "Ajeet", "Steve",
             "Ajeet", "Jon", "Ajeet");

      Map<String, Long> map =
      names.stream().collect(
          Collectors.groupingBy(
             Function.identity(), Collectors.counting()
          )
      );

      System.out.println(map);

   }
}

Output:

{Steve=1, Jon=2, Ajeet=3}

Java – Stream Collectors example of fetching data as List

import java.util.stream.Collectors;  
import java.util.List;  
import java.util.ArrayList;  
class Student{  
   int id;     
   String name;    
   int age;         
   public Student(int id, String name, int age) {  
        this.id = id;    
        this.name = name;         
        this.age = age;     
   } 
}  
public class Example {  
   public static void main(String[] args) {    
      List<Student> studentlist = new ArrayList<Student>();   
      //Adding Students      
      studentlist.add(new Student(11,"Jon",22));      
      studentlist.add(new Student(22,"Steve",18));        
      studentlist.add(new Student(33,"Lucy",22));        
      studentlist.add(new Student(44,"Sansa",23));         
      studentlist.add(new Student(55,"Maggie",18));                  
      //Fetching student names as List       
      List<String> names = studentlist.stream() 
                                   .map(n->n.name) 
                                   .collect(Collectors.toList());
      System.out.println(names);         
   }  
}

Output:

[Jon, Steve, Lucy, Sansa, Maggie]

Java Collectors Example – Collecting Data as Set

In this example we are converting the list of students to the stream and then we are applying the Java Stream filter to get the selected records from the stream, after that we are converting that stream to set using Collectors.toSet() method.

import java.util.stream.Collectors;  
import java.util.List;  
import java.util.Set; 
import java.util.ArrayList;  
class Student{    
   int id;     
   String name;  
   int age;           
   public Student(int id, String name, int age) {   
       this.id = id;         
       this.name = name;       
       this.age = age;      
   } 
}  
public class Example {     
   public static void main(String[] args) {       
      List<Student> studentlist = new ArrayList<Student>();       
      //Adding Students        
      studentlist.add(new Student(11,"Jon",22));         
      studentlist.add(new Student(22,"Steve",18));         
      studentlist.add(new Student(33,"Lucy",22));         
      studentlist.add(new Student(44,"Sansa",23));         
      studentlist.add(new Student(55,"Maggie",18));                  
      //Fetching student data as a Set       
      Set<Student> students = studentlist.stream()
                           .filter(n-> n.id>22)
                           .collect(Collectors.toSet());
      //Iterating Set       
      for(Student stu : students) { 
         System.out.println(stu.id+" "+stu.name+" "+stu.age); 
      }           
   } 
}

Output:

44 Sansa 23
33 Lucy 22
55 Maggie 18

Java Collectors Example – Getting the average age of students using averagingInt() method

import java.util.stream.Collectors;  
import java.util.List;  
import java.util.ArrayList; 
class Student{  
   int id;   
   String name;   
   int age;
   public Student(int id, String name, int age) {  
      this.id = id;   
      this.name = name; 
      this.age = age;  
   } 
}  
public class Example {  
   public static void main(String[] args) {  
      List<Student> studentlist = new ArrayList<Student>();  
      //Adding Students  
      studentlist.add(new Student(11,"Jon",22));   
      studentlist.add(new Student(22,"Steve",18));   
      studentlist.add(new Student(33,"Lucy",22));   
      studentlist.add(new Student(44,"Sansa",23));   
      studentlist.add(new Student(55,"Maggie",18));
      //Getting the average Age 
      Double avgAge = studentlist.stream()   
          .collect(Collectors.averagingInt(s->s.age));  
      System.out.println("Average Age of Students is: "+avgAge);
   }  
}

Output:

Average Age of Students is: 20.6

I have shown the examples of very few methods of Java Collectors class. To get the complete list of methods refer the javadoc: Java 8 Stream Collectors – JavaDoc

❮ PreviousNext ❯

Leave a Reply Cancel reply

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

Java 8 Features

  • Lambda Expressions
  • Method References
  • Functional Interfaces
  • Java 8 Interface changes
  • Java 8 Stream API
  • Stream Filter
  • Java forEach()
  • Collectors Class
  • StringJoiner Class
  • Optional Class
  • Arrays.parallelSort()

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap