BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java 8 – Stream Collectors Class with examples

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

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 ❯

Top Related Articles:

  1. Java 8 features with examples
  2. Java 8 Stream Tutorial
  3. Java 8 Interface Changes – default method and static method
  4. Java 9 – @SafeVarargs Annotation (with examples)
  5. Multilevel inheritance in java with example

Tags: Java8-Features

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap