Monday, June 17, 2024

Filter a Map by Keys and Values using Java Stream

Filter a Map by Keys and Values using Java Stream

Discover how to filter a Map by keys, values, or both using Java 8’s Stream API with the filter() and collect() methods. These straightforward code snippets demonstrate how to create generic functions for filtering any Map based on its keys or values. Let us delve into understanding how to filter a map by keys and values.

1. Introduction


In Java, a Map is a part of the Java Collections Framework and is used to store key-value pairs. Each key in a map is unique, and each key maps to exactly one value. Maps provide a way to look up values based on their corresponding keys, making data retrieval efficient.

Common implementations of the Map interface include HashMap, TreeMap, and LinkedHashMap. These implementations differ in terms of ordering, performance, and underlying data structures. For instance, HashMap offers average constant-time performance for most operations like get and put, while TreeMap maintains a sorted order of keys.

Maps are versatile and widely used in Java applications to manage and manipulate collections of data where relationships between keys and values are important.

1.1 Filter a Map by Keys


To filter a map by keys, we can use the Stream API to process the entries and collect them back into a map. Here is an example:

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
 
public class FilterMapByKey {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("apple", 10);
        map.put("banana", 20);
        map.put("cherry", 30);
        map.put("date", 40);
 
        // Filter the map to keep only keys starting with 'a'
        Map filteredMap = map.entrySet()
            .stream()
            .filter(entry -> entry.getKey().startsWith("a"))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
 
        System.out.println(filteredMap);
    }
}

Here’s a code breakdown:

  • map.entrySet().stream() – Creates a stream from the map’s entry set.
  • filter(entry -> entry.getKey().startsWith("a")) – Filters the entries where the key starts with ‘a’.
  • collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) – Collects the filtered entries back into a map.

The code output is:

{apple=10}

1.2 Filter a Map by Values


Filtering a map by values follows a similar approach. Here is an example:

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
 
public class FilterMapByValue {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("apple", 10);
        map.put("banana", 20);
        map.put("cherry", 30);
        map.put("date", 40);
 
        // Filter the map to keep only values greater than 20
        Map filteredMap = map.entrySet()
            .stream()
            .filter(entry -> entry.getValue() > 20)
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
 
        System.out.println(filteredMap);
    }
}

Here’s a code breakdown:

  • map.entrySet().stream() – Creates a stream from the map’s entry set.
  • filter(entry -> entry.getValue() > 20) – Filters the entries where the value is greater than 20.
  • collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) – Collects the filtered entries back into a map.

The code output is:

{date=40, cherry=30}

1.3 Filter a Map by Keys and Values, Both


Sometimes, you may need to filter a map by both keys and values. Here is how you can do that:

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
 
public class FilterMapByKeyAndValue {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("apple", 10);
        map.put("banana", 20);
        map.put("cherry", 30);
        map.put("date", 40);
 
        // Filter the map to keep only keys starting with 'c' and values greater than 20
        Map filteredMap = map.entrySet()
            .stream()
            .filter(entry -> entry.getKey().startsWith("c") && entry.getValue() > 20)
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
 
        System.out.println(filteredMap);
    }
}

Here’s a code breakdown:

  • map.entrySet().stream() – Creates a stream from the map’s entry set.
  • filter(entry -> entry.getKey().startsWith("c") && entry.getValue() > 20) – Filters the entries where the key starts with ‘c’ and the value is greater than 20.
  • collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) – Collects the filtered entries back into a map.

The code output is:

{cherry=30}

Using the Stream API in Java 8 and later versions, filtering maps by keys, values, or both becomes a clean and efficient process. The examples provided demonstrate how to perform these operations effectively.

2. Conclusion


In conclusion, filtering maps by keys, values, or both in Java can be efficiently accomplished using the Stream API introduced in Java 8. By leveraging the power of streams, developers can create concise and readable code to handle these common tasks. Whether you need to filter entries based on specific key patterns, value ranges, or a combination of both, the examples provided demonstrate the flexibility and ease with which these operations can be performed. This approach not only enhances code readability but also ensures that operations on collections are both functional and expressive.

Source: javacodegeeks.com

Related Posts

0 comments:

Post a Comment