Java 8 forEach examples

  • 07 February 2017
  • ADM

 

Java 8 forEach examples - images/logos/java.jpg

 

In this article will see how to loop through a Map and List using new forEach statement from Java 8.

Map Loop

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("key1", 10);
map.put("key2", 20);
map.put("key3", 30);
map.put("key4", 40);
map.put("key5", 50);
map.put("key6", 60);

map.forEach((k, v) -> System.out.println("key : " + k + ", value : " + v));

or if the forEach block needs to have more than one line.

map.forEach((k, v) -> {
    System.out.println("key : " + k + ", value : " + v);
    /* multiple lines */
    /* ... */
});

Output

key : key1, value : 10
key : key2, value : 20
key : key5, value : 50
key : key6, value : 60
key : key3, value : 30
key : key4, value : 40

List Loop

There are three methods to loop a list:

  • using lambda;
  • using method reference;
  • using stream;
	List<String> list = new ArrayList<String>();
	list.add("Value1");
	list.add("Value2");
	list.add("Value3");
	list.add("Value4");
	list.add("Value5");
	list.add("Value6");
	
	System.out.println();
	System.out.println("Using lambda single line");
	System.out.println();

	/** using lambda - if there is single line */
	list.forEach(v -> System.out.println("Value : " + v));
	
	System.out.println();
	System.out.println("Using lambda multiple lines");
	System.out.println();

	/** using lambda - if there are multiple lines */
	list.forEach(v -> {
	    System.out.println("Value : " + v);
	    /* multiple lines */
	    /* ... */
	});
	
	System.out.println();
	System.out.println("Using method reference");
	System.out.println();

	/** using method reference */
	list.forEach(System.out::println);
	
	System.out.println();
	System.out.println("Using stream and filter");
	System.out.println();

	/** using stream and filter */
	list.stream().filter(s -> s.contains("Value3")).forEach(System.out::println);

Output

Using lambda single line

Value : Value1
Value : Value2
Value : Value3
Value : Value4
Value : Value5
Value : Value6

Using lambda multiple lines

Value : Value1
Value : Value2
Value : Value3
Value : Value4
Value : Value5
Value : Value6

Using method reference

Value1
Value2
Value3
Value4
Value5
Value6

Using stream and filter

Value3

 

References