Java 9 ArrayList how to count number of elements
In this 3 different ways of counting elements of ArrayList are shown:
- Collections.frequency(arrayList, "A3");
- using streams
- private method using streams
In this example:
- count number of occurrences of element with value - A3
- count all elements occurrences
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ArrayListCount {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("A1");
arrayList.add("A2");
arrayList.add("A3");
arrayList.add("A4");
arrayList.add("A3");
arrayList.add("A3");
arrayList.add("A5");
//
// Using frequency method of Collections
//
int frequency = Collections.frequency(arrayList, "A3");
System.out.println(frequency);
//
// Using streams since java 8
//
Map<String, Long> counts =
arrayList.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));
System.out.println(counts);
//
// private method and streams since java 8
//
count(arrayList);
}
private static void count(List<String> items) {
Map<String, Long> result =
items.stream().collect(
Collectors.groupingBy(
Function.identity(), Collectors.counting()
)
);
result.forEach((item, value) -> System.out.println(item + " - " + value));
}
}
result:
3
{A1=1, A2=1, A3=3, A4=1, A5=1}
A1 - 1
A2 - 1
A3 - 3
A4 - 1
A5 - 1