Anand Anand - 2 months ago 17x
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?


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 =
       .mapToObj(i -> (char) i)