Learn java 8 with me(2):Iterate over list and map using stream's forEach
Java 8 introduced a new stream grammar ,which uses inner iteration and supplies many operations like filter/map/count/limit/forEach/count etc. Today ,I would introduce how to use stream’s forEach operation to do list and map iteration.
The old way to do list and map iteration is as follows:
- Firstly ,we define two methods to construct demo list and map
private static List<String> constructList() {
return Arrays.asList("s1","s2","s3");
}
private static Map<String,String> constructMap() {
return new HashMap<String,String>() {
{
put("k1","v1");
put("k2","v2");
put("k3","v3");
}
};
}
As you can see, the constructList method returns a predefined list which constains three elements, And constructMap method return a map contains three key-value pairs.
- Now do the iteration in the old way(before java8):
public static void main(String[] args) {
//demo the old way to iterator over a list and map.
List<String> elements = constructList();
//iterate over a list
for(String element:elements) {
System.out.println(element);
}
Map<String,String> map = constructMap();
//iterate over a map
for(String key:map.keySet()) {
System.out.println(key+"-->"+map.get(key));
}
}
- Run the program,we got this:
s1
s2
s3
k1-->v1
k2-->v2
k3-->v3
In the new java8 way, we iterate the list and map like this:
public static void main(String[] args) {
List<String> elements = constructList();
//iterate over a list
elements.stream().forEach(e->System.out.println(e)); /*line 1*/
//iterate over a map
Map<String,String> map = constructMap();
map.keySet().stream().forEach(k-> System.out.println(k+"-->"+map.get(k))); /*line 2*/
}
The explain:
- the line 1: elements.stream() method returns a Stream object, which has a forEach operation, we can supply a FunctionalInterface Consumer<T>,which consumes an element typed T and return void, here,we supply a lambda e->System.out.println(e); ,this expression equals: (String e)->System.out.println(e)
-
the line 2: map does not supply stream ,so we use the keySet() elements to get the stream object,and then call the forEach
- Run the program,we got this:
s1
s2
s3
k1-->v1
k2-->v2
k3-->v3
You can find detail documents about the java8 and streams here:
The above code examples’ source code is here: