Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write String Iteration with Map Put operations in Java 8?

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.

like image 791
fatherazrael Avatar asked Feb 16 '26 04:02

fatherazrael


2 Answers

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 primitives
  • groupingBy receives a function to get the key to group by and a Collector implementation
  • Function.identity() is just a function that returns whatever element it is passed to it
  • Collectors.counting() is a collector that counts
like image 67
Cristian Avatar answered Feb 18 '26 23:02

Cristian


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.

like image 29
Robby Cornelissen Avatar answered Feb 18 '26 23:02

Robby Cornelissen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!