How to write a counter in Java 8?

Writing a counter in Java can be as simple as 2 lines. In addition to its simplicity, we can also utilize the parallel computation to increase the counter’s performance.

import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Map;
 
public class Java8Counter {
	public static void main(String[] args) {
		String[] arr = { "program", "creek", "program", "creek", "java", "web",
				"program" };
		Stream<String> stream = Stream.of(arr).parallel();
		Map<String, Long> counter = stream.collect(Collectors.groupingBy(
				String::toString, Collectors.counting()));
		System.out.println(counter.get("creek"));
	}
}

When you get the map, you may also want to sort the map by value. Check out this post to see how.

Leave a Comment