I am trying to convert following code into Java 8::
String s = "12345";
Map<Character,Integer> map = new HashMap<Character,Integer>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
int cnt = map.get(c);
map.put(c, ++cnt);
} else {
map.put(c, 1);
}
}
I tried and found following way to iterate:
IntStream.rangeClosed(0, s.length).foreach(d -> {
//all statements from char to map.put
}) ;
I am not sure whether this is correct way to do it.
You can do this:
s.chars()
.mapToObj(x -> (char) x)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
.mapToObj(x -> (char) x) is necessary because .chars() gives you a stream of ints, but in order to use groupingBy you need to work with objects, not primitivesgroupingBy receives a function to get the key to group by and a Collector implementationFunction.identity() is just a function that returns whatever element it is passed to itCollectors.counting() is a collector that counts You can use the groupingBy() and counting() collectors:
String s = "12345";
Map<Character, Long> map = s
.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(map);
Unfortunately, there seems to be no convenient way to get a Stream<Character> from a string, hence the need to map to an IntStream using chars() and then using mapToObj() to convert it to a character stream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With