2

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 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

1

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));

3 Comments

Thank you, but it's not working. This is the result if I run your code: a : 3 b : 3 c : 4 d : 2 z : 2
yes, because in the post you start counting from 1. I have updated it :)
It gets now {a=2, b=2, c=3, d=1, z=1}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.