Tuesday, March 14, 2023

One more Java Streams example for Pat Sajak

Let's help Pat Sajak count how many letters in a phrase for Wheel of Fortune
String str = "This maybe helpful for Pat Sajak";

// Turn the string into a list of characters, upper case it
// then recollect it with a groupby

      Map result =
    		  str
		      .chars()
		      .mapToObj(e -> (char)e)
		      .map(c-> Character.toUpperCase(c))
		      .collect(
                      Collectors.groupingBy(
                              Function.identity(), Collectors.counting()
                      )
              );
              
System.out.println(result);
          
Output:
{ =5, A=4, B=1, E=2, F=2, H=2, I=1, J=1, K=1, L=2, M=1, O=1, P=2, R=1, S=2, T=2, U=1, Y=1}
          

No comments: