1

given

char[] arr = {'a','a','c','d','d','d','d'};

i want to print like this
{a=2,c=1,d=4} using java 8 streams.

using this :

Stream.of(arr).collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))

but its not working.

2 Answers 2

4

The method is Stream.of(char[]) returns a Stream where each element is an array of char, you want a stream of char, there is several methods here

char[] arr = {'a', 'a', 'c', 'd', 'd', 'd', 'd'};

Map<Character, Long> result = IntStream.range(0, arr.length).mapToObj(i -> arr[i])
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

System.out.println(result); // {a=2, c=1, d=4}
Sign up to request clarification or add additional context in comments.

Comments

1
public class CharFrequencyCheck {
public static void main(String[] args) {
    Stream<Character> charArray = Stream.of('a', 'a', 'c', 'd', 'd', 'd', 'd');
    Map<Character, Long> result1 = charArray.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    System.out.println(result1);
}

} // this can be helpful as well :)

Comments

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.