Java 8 - count distinct elements in List

0 points
Created by:
Dirask Community

In this article, we would like to show you how to count distinct elements in List working with Java 8.

Quick solution:

List<String> list = Arrays.asList("A", "B", "C", "B", "A");

long count =;

System.out.println(count);  // 3


Practical example

In this example, we use Stream distinct() and count() methods to count distinct elements in the letters list.

import java.util.*;

public class Example {

    public static void main(String[] args) {
        // create list of strings
        List<String> letters = Arrays.asList("A", "B", "C", "B", "A");

        // count distinct elements in list
        long count =;

        // print result
        System.out.println("Number of distinct elements : " + count);


The number of distinct elements : 3


Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂