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
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):
- Run the program,we got this:
In the new java8 way, we iterate the list and map like this:
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:
You can find detail documents about the java8 and streams here:
The above code examples’ source code is here: