Thursday 31 August 2017

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


Click here to watch in Youtube :
https://www.youtube.com/watch?v=y4dlPsXk3AQ&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 map.
 */
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");

         //Map -> Stream -> Filter -> Map
        Map<Integer, String> filteredMap = fruitsMap.entrySet().stream()
                .filter(map -> map.getKey() == 2)
                .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));

        System.out.println(filteredMap);

    }

}
Output
{2=Orange}

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/53e39342c1c41555c6e548783b3cf96ab7bd9ee6/BasicJava/StreamDemo_filter_fruits_map_return_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