Vishnu Jethliya
Vishnu Jethliya

Reputation: 13

count the frequency of each character in char array using java 8 stream

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.

Upvotes: 1

Views: 1643

Answers (2)

Sudhakar Rathi
Sudhakar Rathi

Reputation: 11

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

Upvotes: 1

azro
azro

Reputation: 54148

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}

Upvotes: 4

Related Questions