1. Using the HashSet class constructor
2. Using Stream API (Java 8)
Read Also: Difference between HashMap and HashSet in Java
Let's dive deep into the topic:
Java Convert Map to Set
1. Using the HashSet class constructor
We can easily convert Map to Set in Java using the HashSet class constructor. In Java, each HashMap element contains key-value pair i.e. two values whereas each HashSet element contains only one value.
According to our requirement, we can convert either map keys or values to a set of keys or set of values as shown below in the example:
import java.util.*;
public class MapToSetExample {
public static void main(String args[]) {
// Creating HashMap Object
Map<Integer, String> map = new HashMap<>();
// Adding elements to the HashMap object
map.put(1, "India");
map.put(2, "USA");
map.put(3, "UK");
map.put(4, "Canada");
map.put(5, "Germany");
// Convert Map keys to Set using constructor
Set<Integer> set1 = new HashSet(map.keySet());
System.out.println("Converted Map keys to Set using constructor: " + set1);
// Convert Map values to Set using constructor
Set<String> set2 = new HashSet(map.values());
System.out.println("Converted Map values to Set using constructor: " + set2);
}
}
Output:
Converted Map keys to Set using constructor: [1, 2, 3, 4, 5]
Converted Map values to Set using constructor: [Canada, USA, UK, Germany, India]
2. Using Stream API (Java8)
We can easily convert Map to Set in Java using Stream API (Java8) as shown below in the example:
import java.util.*;
import java.util.stream.*;
public class MapToSetExample2 {
public static void main(String args[]) {
// Making HashMap Object
Map<Integer, String> map = new HashMap<>();
// Adding elements using HashMap put() method
map.put(11, "Orange");
map.put(12, "Strawberry");
map.put(13, "Apple");
map.put(14, "Banana");
map.put(15, "Grapes");
// Convert Map keys to Set using stream API
Set<Integer> set1 = map.keySet().stream().collect(Collectors.toSet());
System.out.println("Converted Map keys to Set using stream API: " + set1);
// Convert Map values to Set using stream API
Set<String> set2 = map.values().stream().collect(Collectors.toSet());
System.out.println("Converted Map values to Set using stream API: " + set2);
}
}
Output:
Converted Map keys to Set using stream API: [11, 12, 13, 14, 15]
Converted Map values to Set using stream API: [Apple, Grapes, Strawberry, Orange, Banana]
That's all for today. Please mention in the comments if you have any questions related to how to convert Map to Set in Java.