Languages
[Edit]
EN

Java - count distinct values in ArrayList

0 points
Created by:
Huzaifa-Ball
475

In this article, we would like to show you how to count distinct values in ArrayList in Java.

Quick solution:

Set<String> mySet = new HashSet<>(myArrayList);
System.out.println(distinctSet.size());

or

long unique = myArrayList.stream().distinct().count();

 

1. Using HashSet

In this example, we create HashSet from the letters ArrayList to remove duplicates. Then we use size() method to get the number of unique values in letters ArrayList.

Practical example:

import java.util.*;

public class Example {

    public static void main(String[] args) {
        List<String> letters = new ArrayList<>();

        letters.add("A");
        letters.add("A");
        letters.add("A");

        letters.add("B");
        letters.add("B");

        letters.add("C");

        Set<String> distinctSet = new HashSet<>(letters);  // removes duplicates

        System.out.println("Number of unique values: " + distinctSet.size());
    }
}

Output:

Number of unique values: 3

2. Using stream

In this example, we use stream to count distinct values in letters ArrayList.

Note: This solution works only for Java 8 version and higher.

Practical example: 

import java.util.*;

public class Example {

    public static void main(String[] args) {
        List<String> letters = new ArrayList<>();

        letters.add("A");
        letters.add("A");
        letters.add("A");

        letters.add("B");
        letters.add("B");

        letters.add("C");

        long unique = letters.stream()
                .distinct()
                .count();

        System.out.println("Number of unique values: " + unique);
    }
}

Output:

Number of unique values: 3

Alternative titles

  1. Java - count unique values in ArrayList
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java Collections - ArrayList

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.

❤️💻 🙂

Join