java 8 foreach_Java 8 forEach examples

本文介绍了如何利用Java8的forEach方法结合lambda表达式或方法引用来遍历Map和List。通过示例代码展示了传统的for-each循环与Java8新特性的对比,帮助开发者更高效地处理集合数据。
摘要由CSDN通过智能技术生成

In this article, we will show you how to loop a List and a Map with the new Java 8 forEach statement.

1. forEach and Map

1.1 Normal way to loop a Map.

Map 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 entry : items.entrySet()) {

System.out.println("Item : " + entry.getKey() + " Count : " + entry.getValue());

1.2 In Java 8, you can loop a Map with forEach + lambda expression.

Map 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 Normal for-loop to loop a List.

List 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 In Java 8, you can loop a List with forEach + lambda expression or method reference.

List items = new ArrayList<>();

items.add("A");

items.add("B");

items.add("C");

items.add("D");

items.add("E");

//lambda

//Output : A,B,C,D,E

items.forEach(item->System.out.println(item));

//Output : C

items.forEach(item->{

if("C".equals(item)){

System.out.println(item);

});

//method reference

//Output : A,B,C,D,E

items.forEach(System.out::println);

//Stream and filter

//Output : B

items.stream()

.filter(s->s.contains("B"))

.forEach(System.out::println);

References

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值