Map Manipulation Examples using Java Streams

In Java, the Stream API provides powerful ways to manipulate collections, including Map. Though Map itself is not a direct part of the Stream API, you can still use Stream with Map by converting it to a Set of its entries using entrySet(), and then manipulate it as a stream.

Here are some common examples of Map manipulation using streams:

1. Filtering a Map by Keys or Values

You can filter a Map based on conditions applied to keys or values using streams.

Example: Filter Map by Values

import java.util.*;
import java.util.stream.Collectors;

public class MapStreamExample {
    public static void main(String[] args) {
        // Creating a map
        Map<String, Integer> people = new HashMap<>();
        people.put("John", 25);
        people.put("Sara", 22);
        people.put("Mike", 30);
        people.put("Emma", 28);

        // Filter map entries where value (age) is greater than 25
        Map<String, Integer> filteredMap = people.entrySet()
                .stream()
                .filter(entry -> entry.getValue() > 25)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        System.out.println("Filtered Map: " + filteredMap);
    }
}

Output:

Filtered Map: {Mike=30, Emma=28}

2. Transforming a Map (Modifying the Values)

You can transform the values of a map using Stream‘s map operation.

Example: Multiply all values by 2

import java.util.*;
import java.util.stream.Collectors;

public class MapStreamExample {
    public static void main(String[] args) {
        // Creating a map
        Map<String, Integer> products = new HashMap<>();
        products.put("Laptop", 1000);
        products.put("Phone", 800);
        products.put("Tablet", 500);

        // Multiply all prices by 2
        Map<String, Integer> updatedProducts = products.entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey, 
                        entry -> entry.getValue() * 2
                ));

        System.out.println("Updated Prices: " + updatedProducts);
    }
}

Output:

Updated Prices: {Laptop=2000, Phone=1600, Tablet=1000}

3. Sorting a Map by Values

Although Map itself is not sorted, you can sort a Map‘s entries based on values using streams.

Example: Sort Map by Values

import java.util.*;
import java.util.stream.Collectors;

public class MapStreamExample {
    public static void main(String[] args) {
        // Creating a map
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Alice", 85);
        scores.put("Bob", 75);
        scores.put("Charlie", 90);
        scores.put("Dave", 60);

        // Sort the map by values in ascending order
        Map<String, Integer> sortedByValue = scores.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(
                        Map.Entry::getKey, 
                        Map.Entry::getValue,
                        (e1, e2) -> e1, // Merge function (not needed here)
                        LinkedHashMap::new  // To maintain the sorted order
                ));

        System.out.println("Sorted Map: " + sortedByValue);
    }
}

Output:

Sorted Map: {Dave=60, Bob=75, Alice=85, Charlie=90}

4. Converting Map Keys or Values to List

You can extract all keys or values from a map and convert them to a list using streams.

Example: Convert Keys to List

import java.util.*;
import java.util.stream.Collectors;

public class MapStreamExample {
    public static void main(String[] args) {
        // Creating a map
        Map<String, Integer> items = new HashMap<>();
        items.put("Laptop", 1200);
        items.put("Phone", 800);
        items.put("Tablet", 450);

        // Convert keys to a list
        List<String> keys = items.keySet()
                .stream()
                .collect(Collectors.toList());

        System.out.println("Keys: " + keys);
    }
}

Output:

Keys: [Laptop, Phone, Tablet]

Example: Convert Values to List

import java.util.*;
import java.util.stream.Collectors;

public class MapStreamExample {
    public static void main(String[] args) {
        // Creating a map
        Map<String, Integer> items = new HashMap<>();
        items.put("Laptop", 1200);
        items.put("Phone", 800);
        items.put("Tablet", 450);

        // Convert values to a list
        List<Integer> values = items.values()
                .stream()
                .collect(Collectors.toList());

        System.out.println("Values: " + values);
    }
}

Output:

Values: [1200, 800, 450]

5. Merging Two Maps

You can merge two maps using the Stream API by combining the entries of both maps.

Example: Merge Two Maps

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class MapStreamExample {
    public static void main(String[] args) {
        // Creating two maps
        Map<String, Integer> map1 = new HashMap<>();
        map1.put("John", 30);
        map1.put("Sara", 28);

        Map<String, Integer> map2 = new HashMap<>();
        map2.put("Mike", 25);
        map2.put("John", 32);  // Duplicate key (John)

        // Merging the two maps
        Map<String, Integer> mergedMap = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
                .collect(Collectors.toMap(
                        Map.Entry::getKey, 
                        Map.Entry::getValue,
                        (existing, replacement) -> replacement // Resolve conflict by using the new value
                ));

        System.out.println("Merged Map: " + mergedMap);
    }
}

Output:

Merged Map: {John=32, Sara=28, Mike=25}

6. Grouping Map Entries by Value

You can group map entries by value using Collectors.groupingBy().

Example: Grouping by Value

import java.util.*;
import java.util.stream.Collectors;

public class MapStreamExample {
    public static void main(String[] args) {
        // Creating a map
        Map<String, Integer> items = new HashMap<>();
        items.put("Book", 50);
        items.put("Pen", 10);
        items.put("Notebook", 50);
        items.put("Pencil", 10);

        // Grouping map entries by their values
        Map<Integer, List<String>> groupedByValue = items.entrySet()
                .stream()
                .collect(Collectors.groupingBy(
                        Map.Entry::getValue, // Group by value
                        Collectors.mapping(Map.Entry::getKey, Collectors.toList()) // Collect keys as list
                ));

        System.out.println("Grouped Map: " + groupedByValue);
    }
}

Output:

Grouped Map: {50=[Book, Notebook], 10=[Pen, Pencil]}

Conclusion

Java Streams provide a flexible and powerful way to manipulate Map data, allowing for operations such as filtering, transforming, sorting, merging, and grouping. These examples show how you can take advantage of the Stream API to work with Map efficiently.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *