Home » Core Java » Java 8 Stream API – distinct(), count() & sorted() Example

About Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

Java 8 Stream API – distinct(), count() & sorted() Example

Hello. In this tutorial, we will explore the Stream API methods: sorted(), count(), and distinct() methods introduced in Java 8.

1. Introduction

java 8 distinct count

Before diving deep into the practice stuff let us understand the methods we will be covering in this tutorial.

  • The distinct() method returns a stream of unique elements. It is a stateful intermediate operation and returns a new stream. This method uses hashCode() and equals() to get the unique elements
  • The sorted() method returns a stream consisting of elements in the sorted natural order. This method can also accept a comparator to provide customized sorting. It is a stateful intermediate operation and returns a new stream
  • The count() method returns the count of elements in a stream

2. Practice

Let us dive into some practice stuff from here and I am assuming that you already have the Java 1.8 or greater installed in your local machine. I am using JetBrains IntelliJ IDEA as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Model class

Create a java file in the com.java8.util package and add the following code. The class will act as a model class for the creation of the employee list.

Employee.java

package com.java8.util;

import java.util.ArrayList;
import java.util.List;

public class Employee {
    private final String email;
    private final int age;

    private Employee(String email, int age) {
        this.email = email;
        this.age = age;
    }

    public static List<Employee> create() {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee("john@email.com", 21));
        employees.add(new Employee("martin@email.com", 19));
        employees.add(new Employee("marry@email.com", 31));
        employees.add(new Employee("john@email.com", 27));
        employees.add(new Employee("marry@email.com", 25));

        return employees;
    }

    public String getEmail() {
        return email;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Employee [email=" + email + ", age=" + age + "]";
    }
}

2.2 Understanding distinct() method

Create a java file in the com.java8 package and add the following code. The class will show the distinct() method implementation in different ways.

DistinctDemo.java

package com.java8;

import com.java8.util.Employee;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class DistinctDemo {

    // distinct() method returns a stream of unique elements
    // uses the hashCode() and equals() method to get the unique elements

    // removing duplicates from primitive type
    private static void method1() {
        List<Integer> duplicates = Arrays.asList(1, 2, 2, 3, 4, 5, 6, 6, 1, 8, 0, 10);
        print("Original list: ", duplicates);

        List<Integer> unique = duplicates.stream()
                .distinct()
                .collect(Collectors.toList());
        print("Distinct list: ", unique);
    }


    // removing duplicates from object
    private static void method2() {
        List<Employee> employees = Employee.create();
        print("Original list: ", employees);

        List<Employee> distinct = employees.stream()
                .filter(distinctByKey(Employee::getEmail))    // using the predicate to remove the duplicated
                .collect(Collectors.toList());
        print("Distinct list: ", distinct);
    }

    // predicate to filter the duplicates by the given key extractor
    // does the job to remove the duplicates
    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }

    // print the list
    private static void print(String message, List<?> some) {
        System.out.println(message + some);
    }

    // driver code
    public static void main(String[] args) {
        System.out.println("-- Streams distinct() method --\n");

        method1();

        System.out.println("\n");

        method2();
    }
}

Run the file as a java application and if everything goes well the following output will be logged in the IDE console.

Console output

-- Streams distinct() method --

Original list: [1, 2, 2, 3, 4, 5, 6, 6, 1, 8, 0, 10]
Distinct list: [1, 2, 3, 4, 5, 6, 8, 0, 10]


Original list: [Employee [email=john@email.com, age=21], Employee [email=martin@email.com, age=19], Employee [email=marry@email.com, age=31], Employee [email=john@email.com, age=27], Employee [email=marry@email.com, age=25]]
Distinct list: [Employee [email=john@email.com, age=21], Employee [email=martin@email.com, age=19], Employee [email=marry@email.com, age=31]]

2.3 Understanding count() method

Create a java file in the com.java8 package and add the following code. The class will show the count() method implementation in different ways.

CountDemo.java

package com.java8;

import com.java8.util.Employee;

import java.util.Arrays;
import java.util.List;

public class CountDemo {

    // count() method counts the number of elements in the stream

    private static void method1() {
        List<Integer> list = Arrays.asList(1, 2, 2, 3, 4, 5, 6, 6, 1, 8, 0, 10);

        long total = list.stream()
                .count();
        System.out.println("Total elements = " + total);
    }

    private static void method2() {
        List<Employee> employees = Employee.create();

        long total = employees.stream().count();
        System.out.println("Total employees = " + total);

        long freshers = employees.stream()
                .filter(employee -> employee.getAge() <= 21)
                .count();
        System.out.println("Total employees after filter(..) op = " + freshers);
    }

    // driver code
    public static void main(String[] args) {
        System.out.println("-- Streams count() method --\n");

        method1();

        System.out.println("\n");

        method2();
    }
}

Run the file as a java application and if everything goes well the following output will be logged in the IDE console.

Console output

-- Streams count() method --

Total elements = 12


Total employees = 5
Total employees after filter(..) op = 2

2.4 Understanding sorted() method

Create a java file in the com.java8 package and add the following code. The class will show the sorted() method implementation in different ways.

SortedDemo.java

package com.java8;

import com.java8.util.Employee;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortedDemo {

	// sorted() method returns a stream consisting of elements in a sorted order
	// it is a stateful intermediate operation

	// sorting primitive type list
	private static void method1() {
		List<Integer> unsorted = Arrays.asList(1, 2, 2, 3, 4, 5, 6, 6, 1, 8, 0, 10);
		System.out.println("Unsorted stream:" + unsorted);

		List<Integer> sorted = unsorted.stream()
				.sorted()
				.collect(Collectors.toList());
		System.out.println("Sorted stream:" + sorted);
	}

	// sorting object list
	private static void method2() {
		List<Employee> employees = Employee.create();

		List<Employee> sorted = employees.stream()
				.sorted(Comparator.comparing(Employee::getAge))    // sorting the employees by age
				.collect(Collectors.toList());
		System.out.println("Sorted list : " + sorted);
	}

	// driver code
	public static void main(String[] args) {
		System.out.println("-- Streams sorted() method --\n");

		method1();

		System.out.println("\n");

		method2();
	}
}

Run the file as a java application and if everything goes well the following output will be logged in the IDE console.

Console output

-- Streams sorted() method --

Unsorted stream:[1, 2, 2, 3, 4, 5, 6, 6, 1, 8, 0, 10]
Sorted stream:[0, 1, 1, 2, 2, 3, 4, 5, 6, 6, 8, 10]


Sorted list : [Employee [email=martin@email.com, age=19], Employee [email=john@email.com, age=21], Employee [email=marry@email.com, age=25], Employee [email=john@email.com, age=27], Employee [email=marry@email.com, age=31]]

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

4. Summary

In this tutorial, we learned the sorted(), count(), and distinct() methods introduced in java8 programming along with the implementation. You can download the source code from the Downloads section.

5. Download the Project

This was a tutorial on learning and implementing the sorted(), count(), and distinct() methods in Java 8.

Download
You can download the full source code of this example here: Java 8 Stream API – distinct(), count() & sorted() Example

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments