words Count using java 8 Stream


import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


public class countStringUsingStreams {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // 1 way
        List li = Arrays.asList("aba", "aaa", "abc", "aaa", "aba", "abc", "abc");
        Map hm = li.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        hm.entrySet().stream().forEach(h -> {
            System.out.println(h.getKey() + " " + h.getValue());
        });
        // 2nd way
        String s = " java is a programming lang , java have classes , have objects ";
        String[] str = s.split(" ");
        List ls = Arrays.asList(str);
        Map hmap = ls.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        hmap.entrySet().forEach(lstring -> {
            System.out.println(lstring.getKey() + "  " + lstring.getValue());
        });
    }
}

Comments