Home / JAVA Complete Reference by Examples / Streams / How to filter an Map stream using Lambda expression in Java 8 by Example
How to filter an Map stream using Lambda expression in Java 8 by Example
2596 views.
package com.learnbyexamples.streams;

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


/*
 * Find number of keys which has 4 and 3 characters.
 */
public class E003_MapFilterStream {
    public static void main(String[] args) {
        //Simple map of strings
        //{"Arun","Raja","Kumar","Ram","Siva"}
        Map<String, String> names = new HashMap<>();
        names.put("arun", "Arun Kumar");
        names.put("raja", "Raja Ram");
        names.put("kumar", "Dennis kumar");
        names.put("ram", "Ram Kumar");
        names.put("siva", "Sivakumar");
        
        //Convert map entryset into Stream
        Stream<Map.Entry<String, String>> namesStream = names.entrySet().stream();
        
        //Filter 4 Char names gives new stream
        //interface Predicate<T> which has single abstract method - boolean test(T t).
        Stream<Map.Entry<String, String>> namesHas4Chrs = namesStream.filter(entry -> entry.getKey().length() == 4);
        
        Map<String, String> filteredNames = namesHas4Chrs.collect(Collectors.toMap(e -> e.getKey() ,e -> e.getValue()));
        System.out.println(filteredNames);
        
        //If you want to do in single line.
        Map<String, String> hasThreeChrs = names.entrySet().stream().filter(entry -> entry.getKey().length() == 3).collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()));
        System.out.println(hasThreeChrs);
    }
}
Output
{raja=Raja Ram, siva=Sivakumar, arun=Arun Kumar}
{ram=Ram Kumar}
Related Examples
   How to filter an List stream using Lambda expression in Java 8 by Example
   How to filter an Array stream using Lambda expression in Java 8 by Example
   How to filter an Map stream using Lambda expression in Java 8 by Example
   How to use Stream generate method using Lamdba expression in Java 8 Example
   How to read a file line by line using stream in Java 8 by Example
   How to split string into stream in Java 8 by Example
   How to transform stream elements using map in Java 8 by Example
   How to use flatMap stream method in Java 8 by Example
Copyright © 2016 Learn by Examples, All rights reserved