Java 8 forEach examples

Java 8 forEach example

forEach examples for Java 8 are required because Java 8 has come with some new features which makes looping easier. We will see how to loop a Map or a List using forEach statement in Java 8.

In this article, we will show you how to loop a List and a Map with the new Java 8 forEach statement.


Map

Loop a map with lambda expression : Here we will see how to loop through the map with lambda expression.

forEach lambda expression example:

Map<String, Integer> testItems= new HashMap<>();
testItems.put("1", 10);
testItems.put("2", 20);
testItems.put("3", 30);
testItems.put("4", 40);
testItems.put("5", 50);
testItems.put("6", 60);

testItems.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));

testItems.forEach((k,v)->{
    System.out.println("Item : " + k + " Count : " + v);
    if("2".equals(k)){
        System.out.println("Hello 2");
    }
});

In Java 8, you can loop a List with lambda expression or method reference. Let see how we can use forEach and lambda expression to iterate over the list.

List<String> listItems = new ArrayList<>();
listItems.add("A");
listItems.add("B");
listItems.add("C");
listItems.add("D");
listItems.add("E");

listItems.forEach(item->System.out.println(item));
//Output : A,B,C,D,E

listItems.forEach(item->{
    if("D".equals(item)){
        System.out.println(item);
    }
});
//Output : D


Looping through the list using method reference

listItems.forEach(System.out::println);
//Output : A,B,C,D,E

Looping through the list using Stream and filter

listItems.stream().filter(s->s.contains("E")).forEach(System.out::println);

//Output : E

Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment