zoukankan      html  css  js  c++  java
  • java8 查找字符串中首次出现2次的字母

    利用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

  • 相关阅读:
    Hadoop 2.7.1 源代码目录结构分析
    Jit
    java性能分析工具
    最近一个dish项目的建设思考
    mysql的ACID的理解
    实践中积累沟通组织经验
    系统性能--磁盘/网卡
    系统性能--CPU
    调停者模式的批斗
    channel和Stream的对比
  • 原文地址:https://www.cnblogs.com/pu20065226/p/11486251.html
Copyright © 2011-2022 走看看