Java 8 Counter

Before Java 8, developers often think about different ways of writing a counter to count something, e.g., counting word frequency.

In Java 8, you can write a counter in two simple lines! In addition you can take advantage of parallel computing.

Here is Java 8 counter:

package com.programcreek.java8;
 
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"));
	}
}

Leave a Comment