728x90 AdSpace

Wednesday, 21 June 2017

Java 8 forEach with List example

In this article we are going to see about Java 8 forEach with List example program

ForEachList.java
package com.javatutorialcorner.java8;

import java.util.ArrayList;
import java.util.List;

public class ForEachList {

 public static void main(String[] args) {

  List batsmanRanking = new ArrayList<>();
  batsmanRanking.add("Virat Kohli");
  batsmanRanking.add("AB de Villiers");
  batsmanRanking.add("David Warner");
  batsmanRanking.add("Joe Root");
  batsmanRanking.add("Kane Williamson");
  batsmanRanking.add("Quinton de Kock");
  batsmanRanking.add("Faf du Plessis");
  batsmanRanking.add("Babar Azam");
  batsmanRanking.add("Martin Guptill");
  batsmanRanking.add("Shikhar Dhawan");

  System.out.println("Java 7 forEach : ICC One day Batsman Ranking");

  // Java 7 for each
  for (String batsman : batsmanRanking) {
   System.out.println("Name : " + batsman);

  }

  System.out.println("Java 8 forEach with lambda Expression : ICC One day Batsman Ranking");

  // lambda Expression
  batsmanRanking.forEach(item -> System.out.println(item));

  // Output : C
  batsmanRanking.forEach(item -> {
   if ("AB de Villiers".equals(item)) {
    System.out.println(item);
   }
  });

  System.out.println("Java 8 forEach with method reference : ICC One day Batsman Ranking");

  // method reference
  batsmanRanking.forEach(System.out::println);

  System.out.println("Java 8 forEach with Stream and filter : ICC One day Batsman Ranking");

  // Stream and filter
  batsmanRanking.stream().filter(s -> s.contains("AB de Villiers")).forEach(System.out::println);
 }

}

Output
Java 7 forEach : ICC One day Batsman Ranking
Name : Virat Kohli
Name : AB de Villiers
Name : David Warner
Name : Joe Root
Name : Kane Williamson
Name : Quinton de Kock
Name : Faf du Plessis
Name : Babar Azam
Name : Martin Guptill
Name : Shikhar Dhawan
Java 8 forEach with lambda Expression : ICC One day Batsman Ranking
Virat Kohli
AB de Villiers
David Warner
Joe Root
Kane Williamson
Quinton de Kock
Faf du Plessis
Babar Azam
Martin Guptill
Shikhar Dhawan
AB de Villiers
Java 8 forEach with method reference : ICC One day Batsman Ranking
Virat Kohli
AB de Villiers
David Warner
Joe Root
Kane Williamson
Quinton de Kock
Faf du Plessis
Babar Azam
Martin Guptill
Shikhar Dhawan
Java 8 forEach with Stream and filter : ICC One day Batsman Ranking

AB de Villiers

Annamalai Thangaraj

Annamalai is working as Technical Lead in Leading Telecom company with 5+ years experience in Identity and Access Management , Telecom and Networks, BigData, Java, Spring, Struts, Hibernate, AngularJS, and Enterprise Web Application Development.

Website: Java Tutorials Corner

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Java 8 forEach with List example Rating: 5 Reviewed By: Annamalai Thangaraj