Java Stream collect to find element frequency

Description

Java Stream collect to find element frequency



import java.security.SecureRandom;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {
   public static void main(String[] args) {
      SecureRandom random = new SecureRandom();

      System.out.printf("%-6s%s%n", "Face", "Frequency");
      random.ints(6_000_000, 1, 7)//  ww w.ja va  2  s . c  o  m
            .boxed()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            .forEach((face, frequency) -> System.out.printf("%-6d%d%n", face, frequency));
   }
}



PreviousNext

Related