How to convert this Java code into Lambda and Stream implementation?

Viewed 70

I have an implementation to find duplicate characters in a String:

Map<Character, Integer> charMap = new HashMap<>();
for (int i = 0; i < word.length(); i++) {
    Character ch = word.charAt(i);
    if (charMap.containsKey(ch)) {
        charMap.put(ch, charMap.get(ch) + 1);
    } else {
        charMap.put(ch, 1);
    }
}

I want to know if I can convert this implementation into an Java 8 and Stream implementation. To do something like this:

Map<Character, Integer> charMap = new HashMap<>();

Then convert the String word into a List of characters:

List<Character> chars = word.chars()
        .mapToObj(i -> (char) i)
        .collect(Collectors.toList());

And now to do something like that:

chars.stream()
        .filter(e -> charMap.containsKey(e))...
3 Answers

You don't need streams here. Just write a for loop. Here's how it looks.

Map<Character, Integer> chCntMap = new HashMap<>();
for (char ch : word.toCharArray())
    chCntMap.merge(ch, 1, Integer::sum);

I want to know if I can convert this implementation into an Java 8 and Stream implementation.

word.chars()
    .mapToObj(i->(char)i)
    .collect(groupingBy(Function.identity(), counting())); // Map<Character, Long>

or if you want the values as Integer:

word.chars()
    .mapToObj(i->(char)i)
    .collect(groupingBy(Function.identity(), summingInt(v -> 1))); // Map<Character, Integer>

or via toMap

word.chars()
    .mapToObj(i->(char)i)
    .collect(toMap(Function.identity(), v -> 1, Integer::sum)); // Map<Character, Integer>

You can use this:

        Map<Character, Integer> charMap = new HashMap<>();
        String word = "acbczabcd";
        word.chars().forEach(ch -> charMap.put((char) ch, charMap.getOrDefault((char) ch, 0) + 1));

, with mapToObj

word.chars().mapToObj(n -> (char) n).forEach(ch -> charMap.put(ch, charMap.getOrDefault(ch, 0) + 1));
Related