简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM