EN
Java - count distinct values in ArrayList
0
points
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