java8 查找字符串中首次出现2次的字母
2024-10-07 08:04:34
利用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
最新文章
- 15天玩转redis —— 第九篇 发布/订阅模式
- npoi批量导入实现及相关技巧
- SqlIO优化
- C/C++基础总结
- 实现简单的cp命令
- 编译时IOS Device 无法选择的情况
- ArrayList、LinkedList、HashMap底层实现
- Oracle10g、 Oracle11g完美共存
- Red Hat Enterprise Linux x86-64 上安装 oracle 11gR2
- couldn&#39;t connect to the device trackpad
- Ch06 验证
- getuid和geteuid的区别
- Java 错误:找不到或无法加载主类
- [ExtJS5学习笔记]第二十二节 Extjs5中使用beforeLabelTpl配置给标签增加必填选项星号标志
- Openlayer 3加载本地ArcGIS切片
- 遇到的Cocos2dx问题
- Swift.Operator-and-Items-in-Swift(1)
- session 详细解析(转)
- 福州大学软件工程1816 | W班 第5次作业成绩排名
- Zephyr学习(三)启动过程