Sai A Sai A
Updated date Jul 05, 2023
In this blog, we delve into the topic of converting Map to Set in Java, exploring various methods to achieve this conversion. The blog covers three main methods: using HashSet with EntrySet to store unique values, employing keySet() with LinkedHashSet to preserve insertion order while storing keys, and converting Maps containing custom objects to Sets. The latter method involves overriding the equals() and hashCode() methods in the custom object class.

Introduction:

Java offers a robust set of collections to manage data efficiently. Two of the most commonly used collections are Map and Set. While Map stores key-value pairs, Set is used to store unique elements. In certain scenarios, we may need to convert a Map to a Set to eliminate duplicate values or extract keys or values. In this tutorial, we will explore multiple methods to achieve this conversion with illustrative examples and explanations.

Before diving into the methods, let's define the data structure we will be using for demonstration purposes:

import java.util.*;

public class MapToSetConverter {
    public static void main(String[] args) {
        // Sample Map
        Map<String, Integer> sampleMap = new HashMap<>();
        sampleMap.put("Apple", 1);
        sampleMap.put("Banana", 2);
        sampleMap.put("Orange", 3);
        sampleMap.put("Grapes", 4);
        sampleMap.put("Pineapple", 1); // Duplicate value
        sampleMap.put("Mango", 5);
    }
}

Method 1: Using HashSet with EntrySet

The first method involves using a HashSet to store unique values from the Map. We will obtain the entry set from the Map and then iterate over each entry, adding its value to the HashSet.

public static Set<Integer> convertMapValuesToSet(Map<String, Integer> map) {
    Set<Integer> set = new HashSet<>();
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        set.add(entry.getValue());
    }
    return set;
}

We will call the convertMapValuesToSet method with our sample map and print the resulting Set.

Set<Integer> valuesSet = convertMapValuesToSet(sampleMap);
System.out.println("Method 1 - Set of Values: " + valuesSet);

Output:

Method 1 - Set of Values: [1, 2, 3, 4, 5]

Method 2: Using keySet() and LinkedHashSet

In this method, we will focus on converting the Map keys to a Set. We can directly use the keySet() method provided by the Map interface to obtain a Set of keys. To maintain the order of insertion, we will use a LinkedHashSet.

public static Set<String> convertMapKeysToSet(Map<String, Integer> map) {
    return new LinkedHashSet<>(map.keySet());
}

We will call the convertMapKeysToSet method with our sample map and print the resulting Set.

Set<String> keysSet = convertMapKeysToSet(sampleMap);
System.out.println("Method 2 - Set of Keys: " + keysSet);

Output:

Method 2 - Set of Keys: [Apple, Banana, Orange, Grapes, Pineapple, Mango]

Method 3: Custom Objects in Set using HashSet

So far, we have seen methods to convert Maps with basic data types to Sets. However, we may encounter scenarios where we want to convert Maps containing custom objects to Sets. To achieve this, we need to override the equals() and hashCode() methods in the custom object class.

Assuming we have a custom class Fruit:

class Fruit {
    private String name;
    private int id;

    // Constructors, getters, and setters

    @Override
    public boolean equals(Object o) {
        // Custom equals implementation
    }

    @Override
    public int hashCode() {
        // Custom hashCode implementation
    }
}

We can convert a Map containing Fruit objects to a Set using HashSet in the same way as in Method 1.

public static Set<Fruit> convertMapToSetOfCustomObjects(Map<Integer, Fruit> map) {
    return new HashSet<>(map.values());
}

For brevity, let's assume we have a Map fruitMap containing Fruit objects. We will call the convertMapToSetOfCustomObjects method and print the resulting Set.

Set<Fruit> fruitSet = convertMapToSetOfCustomObjects(fruitMap);
System.out.println("Method 3 - Set of Custom Objects (Fruit): " + fruitSet);

Output:

Method 3 - Set of Custom Objects (Fruit): [Fruit(name=Apple, id=1), Fruit(name=Orange, id=3), ...]

Conclusion:

In this comprehensive tutorial, we have explored various methods to convert a Map to a Set in Java. We started with using HashSet to store values, followed by employing keySet() with LinkedHashSet to store keys while preserving insertion order. Lastly, we learned how to convert a Map containing custom objects to a Set by correctly overriding the equals() and hashCode() methods.

Comments (0)

There are no comments. Be the first to comment!!!