The use of java8 ForEach in map and list
the original use
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 ("Key:" +entry.getkey () +; Value: "+entry.getvalue ());
}
Output
A---
B---
C---
D---
E---
F---60
ForEach How to use
Items.foreach ((k,v)->system.out.println ("key:" + K +); Value: "+ V");
Output
key:a value:10
key:b value:20
key:c value:30
key:d value:40 key:e valu
E:50
key:f value:60
Items.foreach ((k,v)->{
System.out.println ("Item:" + k + "Count:" + V);
if ("E". Equals (k)) {
System.out.println ("Hello E");
}
);
key:a; Value:10
key:b; value:20 key:c; value:30 key:d value:40;
key:e
Hello E
how the Java8 List was originally used
list<string> arrayList = new arraylist<> ();
Arraylist.add ("A");
Arraylist.add ("B");
Arraylist.add ("C");
Arraylist.add ("D");
Arraylist.add ("E");
for (String item:arraylist) {
System.out.println (item);
}
java8 ForEach mode of Use
Arraylist.foreach (ITEM->SYSTEM.OUT.PRINTLN (item));
Arraylist.foreach (System.out::p rintln);
Arraylist.foreach (item->{
if ("C". Equals (item)) {
System.out.println (item);
}
);
Arraylist.stream ()
. Filter (s-> s.contains ("B") | | S.contains ("C"))
. ForEach (system.out::p rintln);
Arraylist.stream ()
. Filter (S->s.contains ("E"))
. FindFirst (). Ifpresent (S-> System.out.println (s) );
Reference examples
Java8-foreach-examples
Ibm-java8-stream