Java 8 forEach examples

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

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

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

	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,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

  1. Java 8 Iterable forEach JavaDoc
  2. Java 8 forEach JavaDoc

上一篇: How to set JAVA_HOME on Windows 10?
下一篇: Java Generate random integers in a range
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章来源于互联网, 若有侵权, 联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布文章.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号