1.1 usually traverse a map like this
map<string, integer> items = new hashmap<> (), Items.put ("A", "ten"), Items.put ("B"), Items.put ("C", 30); 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
map<string, integer> items = new hashmap<> (), Items.put ("A", "ten"), Items.put ("B"), Items.put ("C", 30); 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");} });
2. ForEach and List
2.1 Usually traverse a list like this.
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 Java8 you can use the foreach + lambda expression or the method reference (methods 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,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);
Reference Documentation:
- Java 8 iterable ForEach JavaDoc
- Java 8 ForEach JavaDoc
Java 8 foreach Simple example