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);