ForEach and Map
1.1 usually traverse a map like this
New Hashmap<>(), Items.put ("A", "ten"), Items.put ("B"), Items.put ("C", +); Items.put("D", +); Items.put ("E", "a"); Items.put ("F" , "a"); for (map.entry<string, integer> entry:items.entrySet ()) { System.out.println ("Item:" + entry.getkey () + "Count:" + Entry.getvalue ());}
1.2 In Java8 You can use the Foreach + lambda expression to traverse
New Hashmap<>(), Items.put ("A", "ten"), Items.put ("B"), Items.put ("C", +); Items.put("D", +); Items.put ("E", "a"), Items.put ("F", "a"); 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");} });
ForEach and List
2.1 Usually traverse a list like this.
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 Java8 You can use the Foreach + lambda expression or the method reference (methods Reference)
list<string> items =NewArraylist<>(); 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::p rintln);//Stream and Filter//output:bItems.stream (). Filter (S->s.contains ("B") . ForEach (system.out::p rintln);
On the issue of efficiency, the Internet has the great God to test, summed up: the fastest is to enhance the For loop
Final conclusion
Normal (order of magnitude 10W, non-parallel) traverse a collection (List, Set, MAP) If you care about efficiency, do not use Java8 foreach, although it is very convenient and elegant
Any time you use the enhanced for loop you are not the second choice
Reference Documentation:
1.Java 8 iterable ForEach JavaDoc
2.Java 8 ForEach JavaDoc
Transferred from: http://www.cnblogs.com/billyu/p/6118008.html
Java 8 foreach Simple example (reprint)