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

Time:12-05

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.

CodePudding user response:

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}

CodePudding user response:

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

  • Related