728x90 AdSpace

Wednesday, 21 June 2017

Java 8 forEach with Map Example

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

ForEachMap.java
 
package com.javatutorialcorner.java8;

import java.util.HashMap;
import java.util.Map;

public class ForEachMap {

 public static void main(String[] args) {
  Map<String, Integer> batsmanRanking = new HashMap<String, Integer>();
  batsmanRanking.put("Virat Kohli", 1);
  batsmanRanking.put("AB de Villiers", 2);
  batsmanRanking.put("David Warner", 3);
  batsmanRanking.put("Joe Root", 4);
  batsmanRanking.put("Kane Williamson", 5);
  batsmanRanking.put("Quinton de Kock", 6);
  batsmanRanking.put("Faf du Plessis", 7);
  batsmanRanking.put("Babar Azam", 8);
  batsmanRanking.put("Martin Guptill", 9);
  batsmanRanking.put("Shikhar Dhawan", 10);

  System.out.println("ICC One day Batsman Ranking");
  //Normal For each
  for (Map.Entry entry : batsmanRanking.entrySet()) {
   System.out.println("Name : " + entry.getKey() + " Rank : " + entry.getValue());
  }
  
  //Java 8 For Each
  System.out.println("Java 8 forEach ICC One day Batsman Ranking");
  batsmanRanking.forEach((k,v)->System.out.println("Name : " + k + " Rank : " + v));

  System.out.println("Java 8 forEach with condtion ICC One day Batsman Ranking ");
  
  batsmanRanking.forEach((k,v)->{
   
   if("AB de Villiers".equals(k)){
    System.out.println("Hello AB de Villiers");
   }
  });
 }

}
Output :
ICC One day Batsman Ranking
Name : Faf du Plessis Rank : 7
Name : Virat Kohli Rank : 1
Name : Martin Guptill Rank : 9
Name : Babar Azam Rank : 8
Name : Quinton de Kock Rank : 6
Name : Kane Williamson Rank : 5
Name : AB de Villiers Rank : 2
Name : Joe Root Rank : 4
Name : David Warner Rank : 3
Name : Shikhar Dhawan Rank : 10
Java 8 forEach ICC One day Batsman Ranking
Name : Faf du Plessis Rank : 7
Name : Virat Kohli Rank : 1
Name : Martin Guptill Rank : 9
Name : Babar Azam Rank : 8
Name : Quinton de Kock Rank : 6
Name : Kane Williamson Rank : 5
Name : AB de Villiers Rank : 2
Name : Joe Root Rank : 4
Name : David Warner Rank : 3
Name : Shikhar Dhawan Rank : 10
Java 8 forEach with condtion ICC One day Batsman Ranking
Hello 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 Map Example Rating: 5 Reviewed By: Annamalai Thangaraj