Anand Anand - 3 months ago 34
Scala Question

Fold operation in Scala Vs Java 8

How to perform the below Scala operation to find the most frequent character in a string in java 8?

val tst = "Scala is awesomestttttts"
val op = tst.foldLeft(Map[Char,Int]())((a,b) => {
a+(b -> ((a.getOrElse(b, 0))+1))
}).maxBy(f => f._2)


Here the output is

(Char, Int) = (t,6)


I was able to get a stream of characters in Java 8 like this:

Stream<Character> sch = tst.chars().mapToObj(i -> (char)i);


but not able to figure out whats the fold/foldLeft/foldRight alternative we have in Java 8

Can someone pls help?

Answer

Something like this seems to match with the Scala code you provided (if I understand it correctly):

String tst = "Java is awesomestttttts";
Optional<Map.Entry<Character, Long>> max =
    tst.chars()
       .mapToObj(i -> (char) i)
       .collect(Collectors.groupingBy(Function.identity(),
                                      Collectors.counting()))
       .entrySet()
       .stream()
       .max(Comparator.comparing(Map.Entry::getValue));
System.out.println(max.orElse(null));