Java 8 ForEach Example __java

Source: Internet
Author: User

In this article, we'll show you how to loop through a list and a map with the Java 8 new features ForEach.

1. ForEach and Map

1.1 Normal way to loop a Map.

	map<string, integer> items = new hashmap<> ();
	Items.put ("A");
	Items.put ("B");
	Items.put ("C");
	Items.put ("D",);
	Items.put ("E", m);
	Items.put ("F",);

	For (map.entry<string, integer> entry:items.entrySet ()) {
		System.out.println ("Item:" + entry.getkey () + "Co") UNT: "+ entry.getvalue ());
	}

1.2 In Java 8, you can loop through a map with a foreach + lambda expression.

	map<string, integer> items = new hashmap<> ();
	Items.put ("A");
	Items.put ("B");
	Items.put ("C");
	Items.put ("D",);
	Items.put ("E", m);
	Items.put ("F",);
	
	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 Normally use a For loop to loop through 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 through a list with a ForEach + lambda expression or a 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::p rintln); Stream and Filter//output:b Items.stream (). Filter (S->s.contains ("B")). ForEach (System.out::p rintln); 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.