How to Convert a Map to Set in Java

In this post, we will learn as how to Convert a Map to Set in Java.We will see how to do this using JDK.

 

1. Conventional Method

To convert, Java Map to Set, we can use the conventional constructor with HashSet, however, there are few things to consider before we proceed with the conversion. 

 Java Map has 2 values while Set contains only single value while converting Map to Set, we need to take a call of converting either map values or keys, so either we will get a set of keys or set of values (we can get both by using some wrapper to have both values).

public class MapToSet {

    public static void main(String[] args) {

        Map<Integer,String> map= getMap();

        //Convert Map keys to Set
        Set<Integer> keySet= new HashSet<Integer>(map.keySet());
        keySet.forEach(key-> System.out.println(key));

        //Convert Map values to Set
        Set<String> valueSet= new HashSet<String>(map.values());
        valueSet.forEach(value-> System.out.println(value));

    }

    static Map<Integer,String> getMap(){

        Map<Integer, String> sampleMap=new HashMap<Integer,String>();
        sampleMap.put(1,"Sunday");
        sampleMap.put(2,"Monday");
        sampleMap.put(3,"Tuesday");
        sampleMap.put(4,"Wednesday");

        return sampleMap;
    }
}

Output for the above programme will be

1
2
3
4

For valueMap

Sunday
Monday
Tuesday
Wednesday

 

2. Convert a Map to Set in Java 8

We can also use Java 8 Stream API to convert Map to Set in Java.

public class MapToSetJava8 {
    public static void main(String[] args) {

        Map<Integer,String> map= getMap();

        Set keySet=map.keySet().stream().collect(Collectors.toSet());
        keySet.forEach(key-> System.out.println(key));

        Set valueSet=map.values().stream().collect(Collectors.toSet());
        valueSet.forEach(value-> System.out.println(value));
    }

    static Map<Integer,String> getMap(){

        Map<Integer, String> sampleMap=new HashMap<Integer,String>();
        sampleMap.put(1,"Sunday");
        sampleMap.put(2,"Monday");
        sampleMap.put(3,"Tuesday");
        sampleMap.put(4,"Wednesday");

        return sampleMap;
    }
}

My preference will be for the constructor based approach as it is more straight forward and easy to read rather than the Java 8 Stream API.

 

Summary

In this post, we explored as to how to convert a Map to Set in Java, we learned how to convert it using a constructor and Java 8 Stream API.Please read to see how to convert Map to List in Java. All the code of this article is available Over on Github. This is a Maven-based project.