Java 8 forEach 例子
来源:互联网 发布:centos 文件夹扩容 编辑:程序博客网 时间:2024/06/05 11:24
在这边文章中,我们将向你展示怎样用java 8 新特性 forEach
去循环一个List和一个Map。
1. forEach and Map
1.1 正常方式去循环一个 Map.
Map<String, Integer> items = new HashMap<>();items.put("A", 10);items.put("B", 20);items.put("C", 30);items.put("D", 40);items.put("E", 50);items.put("F", 60);for (Map.Entry<String, Integer> entry : items.entrySet()) {System.out.println("Item : " + entry.getKey() + " Count : " + entry.getValue());}
1.2 在java 8 中,你能用forEach
+ lambda 表达式去循环一个Map.
Map<String, Integer> items = new HashMap<>();items.put("A", 10);items.put("B", 20);items.put("C", 30);items.put("D", 40);items.put("E", 50);items.put("F", 60);items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));items.forEach((k,v)->{System.out.println("Item : " + k + " Count : " + v);if("E".equals(k)){System.out.println("Hello E");}});
2. forEach and List
2.1 正常用一个for循环去循环一个 List.
List<String> items = new ArrayList<>();items.add("A");items.add("B");items.add("C");items.add("D");items.add("E");for(String item : items){System.out.println(item);}
2.2 在 Java 8中, 你能用 forEach
+ lambda 表达式或者方法引用去循环一个List.
List<String> items = new ArrayList<>();items.add("A");items.add("B");items.add("C");items.add("D");items.add("E");//lambda//Output : A,B,C,D,Eitems.forEach(item->System.out.println(item));//Output : Citems.forEach(item->{if("C".equals(item)){System.out.println(item);}});//method reference//Output : A,B,C,D,Eitems.forEach(System.out::println);//Stream and filter//Output : Bitems.stream().filter(s->s.contains("B")).forEach(System.out::println);
阅读全文
0 0
- Java 8 forEach 例子
- Java 8 forEach examples
- Java 8 forEach 示例
- Java 8 foreach
- Java 8 forEach 示例
- Java 8 forEach使用
- Java中Set、List、Map、foreach简单例子
- java 8中forEach遍历
- java-foreach
- JAVA foreach
- Java foreach
- Java foreach
- java foreach
- Java foreach
- java foreach
- java foreach
- boost foreach库的例子
- foreach高效并行的例子
- 看后总结(Introduction to Computer Science and Programming,MIT 600)
- Spring MVC和Struts你选哪个?
- C++第七次实验---作业报告
- MyFlag Step6:好友信息的处理
- shell中的ps命令详解
- Java 8 forEach 例子
- Python学习笔记之:文件基本操作
- TOGGLE_BOTTON控件
- Shell test命令
- 贪心法之TSP问题
- POJ2184-Cow Exhibition
- linux vi操作
- Kafka学习总结(六)——应用开发
- Python 地图坐标的转换