Java 8 Stream filter map by keys

In this source code example, we show how to filter a map by its keys in Java 8 with an exmaple.

Java 8 Stream filter map by keys

The example filters domain names starting with s letter.:


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

public class JavaStreamFilterMapByKeys {

    public static void main(String[] args) {

        Map hmap = new HashMap<>();
        
        hmap.put("de", "Germany");
        hmap.put("in", "India");
        hmap.put("sk", "Slovakia");
        hmap.put("si", "Slovenia");
        hmap.put("so", "Somalia");
        hmap.put("us", "United States");
        hmap.put("ru", "Russia");
        
        hmap.entrySet().stream().filter(map -> map.getKey().startsWith("s"))
                .forEach(m -> System.out.println(m));
    }
}

Output:

si=Slovenia
sk=Slovakia
so=Somalia

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments