• Breaking News

    Saturday 26 September 2015

    Java-8 Lambda Expression Tutorial - Iterate Over Map Using Lambda Expression

    A map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.

    In java we iterate over map using for each loop.But in java 8 we can iterate over map in another way using lambda Expression.

    Below is Simple Example of How Iterate over map using classic method and lambda expression.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    package com.kodemaker;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class IterateOverMapUsingLambdaExpression {
    
     public static void main(String[] args) {
      
      Map<Integer,String> mapOfStudent = new HashMap<Integer,String>(){{ put(1 ,"A");
       put(2 ,"B");
       put(3 ,"C");}};
       
      //Simple Iteration Method over map 
      System.out.println("Simple Method -");
      for(Integer key : mapOfStudent.keySet()){
       System.out.println("key :"+key+" Value :"+mapOfStudent.get(key));
      }
      
      //Iterate over map using lambda expression
      System.out.println("Using Lambda Expression -");
      mapOfStudent.forEach((key, value) ->System.out.println("key :"+key+" Value :"+mapOfStudent.get(key)));
     }
    
    }
    

    Output :-

    Simple Method -
    key :1 Value :A
    key :2 Value :B
    key :3 Value :C
    Using Lambda Expression -
    key :1 Value :A
    key :2 Value :B
    key :3 Value :C
    

    No comments:

    Post a Comment