Thursday, 31 August 2017

How to filter a Map and return a String value using Java 8 streams | Streams in Java 8


Click here to watch in Youtube : 
https://www.youtube.com/watch?v=HZq-KpXKieg&list=UUhwKlOVR041tngjerWxVccw

StreamDemo.java
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 
 * Example to filter a Map and return a value.
 */
public class StreamDemo
{
    public static void main(String[] args)
    {

        Map<Integer, String> fruitsMap = new HashMap<>();
        fruitsMap.put(1, "Apple");
        fruitsMap.put(2, "Orange");
        fruitsMap.put(3, "Banana");

        String result = "";
        for (Map.Entry<Integer, String> entry : fruitsMap.entrySet())
        {
            if (2 == entry.getKey())
            {
                result = entry.getValue();
            }
        }
        System.out.println("Before Java 8 : " + result);

        // Map -> Stream -> Filter -> String
        result = fruitsMap.entrySet().stream()
                .filter(map -> 2 == map.getKey())
                .map(map -> map.getValue())
                .collect(Collectors.joining());

        System.out.println("With Java 8 : " + result);

    }

}
Output
Before Java 8 : Orange
With Java 8 : Orange

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/StreamDemo_filter_fruits_map.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/StreamDemo_filter_fruits_map

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/53e39342c1c41555c6e548783b3cf96ab7bd9ee6/BasicJava/StreamDemo_filter_fruits_map/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment