利用java8的stream函数式编程进行处理

1.实现字母分离

map将整个字符串当成一个单词流来处理

Map<String[], Long> collect14 = Stream.of("hello word how are you")
                .map(o -> o.split(""))
//                .flatMap(Arrays::stream)
                .collect(Collectors.groupingBy(o -> o, Collectors.counting()));
 System.out.println(JSONObject.toJSONString(collect14));

输出:{["h","e","l","l","o"," ","w","o","r","d"," ","h","o","w"," ","a","r","e"," ","y","o","u"]:1}

2.实现字符串中字母重复频率统计,利用flatMap对流进行扁平化处理(flatMap与map的不同见java8 stream编程第6点图解)

Map<String, Long> collect14 = Stream.of("hello word how are you")
                .map(o -> o.split(""))
                .flatMap(Arrays::stream)//将前面得到的带大括号的单词流转为字符流
                .collect(Collectors.groupingBy(o -> o, Collectors.counting()));
        System.out.println(JSONObject.toJSONString(collect14));

输出:{" ":4,"a":1,"r":2,"d":1,"u":1,"e":2,"w":2,"h":2,"y":1,"l":2,"o":4}

3.将map的entry转为stream,对map中的kv进行过滤

String collect14 = Stream.of("hello word how are you")
                .map(o -> o.split(""))
                .flatMap(Arrays::stream)
                .collect(Collectors.groupingBy(o -> o, Collectors.counting()))
                .entrySet()
                .stream()
                .filter(o -> o.getValue() == 2)
                .limit(1)
                .map(o -> o.getKey())
                .collect(Collectors.joining());
        System.out.println(collect14);

输出:r

posted on 2019-09-08 14:54  pu20065226  阅读(733)  评论(0编辑  收藏  举报