Home > OS >  use java stream to find count of each character in a string
use java stream to find count of each character in a string

Time:08-31

we have this string: String input1 = "abbccd";

expected output: ab2c2d (note: if count=1, it shouldn't show in output).

the following code outputs a1,b2 c2 d2 on separate lines. Any suggestion to fix and improve?

input1.chars()
      .mapToObj(s -> Character.toLowerCase(Character.valueOf((char) s)))
      .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
      .entrySet().stream()
      .forEach(n -> {System.out.println(n.getKey() "" n.getValue());});

CodePudding user response:

Make the last forEach a map instead.

Instead of n.getValue() only add that part if n.getValue is not 1.

Then collect by joining.

At that point you will have a string you can print.

So, assuming we don't want to change your first part:

"abbccd".chars()
        .mapToObj(s -> Character.toLowerCase((char)s)) // notice here Character.valueOf was redundant, we're already dealing with a char
        .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
        .entrySet().stream()
        .map(n -> n.getKey() "" (n.getValue() == 1 ? "" : n.getValue()))
        .collect(Collectors.joining());

Results in ab2c2d.

CodePudding user response:

Unfortunately, the other two Answers both fail with most characters.

Avoid legacy type char

The char type is legacy, essentially broken since Java 2, legacy since Java 5. As a 16-bit value, char is physically incapable of representing most of the 144,697 characters defined in Unicode.

See one Answer’s code break:

String input = "           
  • Related