How do I convert List to Set in Java
Published May 09, 2022In Java, the ArrayList class allows duplicate entries while maintaining their order, while the HashSet class uses a Hashtable (an implementation class of Set) to prevent duplicate entries. Here are two ways you can use to convert a list to a set:
a) Using a constructor
b) Using the naïve method
Using a constructor
The simplest method for converting a list into a HashSet. Using this method, we create an ArrayList object and pass it to the constructor of HashSet.
Example
package convert_list_to_set_using_constructor; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class convert_list_to_set_using_constructor { public static <T> Set<T> convertListToSet(List<T> list) { return new HashSet<>(list); } public static void main(String[] args) { List<String> list = Arrays.asList("Toyota", "Mazda", "Mitsubishi", "Nissan", "Subaru", "audi"); System.out.println("Our List: " + list); Set<String> set = convertListToSet(list); System.out.println("The Converted Set from List: " + set);
} } |
Output
Our List: [Toyota, Mazda, Mitsubishi, Nissan, Subaru, audi] The Converted Set from List: [audi, Toyota, Subaru, Mazda, Mitsubishi, Nissan] |
The naïve approach
The naive approach involves creating an empty set and then adding each List element to the newly created Set.
Example
import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class Naive_approach_method_to_convert_list_to_set { public static <T> Set<T> convertListToSet(List<T> list) { Set<T> set = new HashSet<>(); for (T t : list) set.add(t); return set; }
public static void main(String[] args) { List<String> list = Arrays.asList("Mangoes", "Oranges", "Apples", "Kiwi", "Citrus", "lemon");
System.out.println(" Our List: " + list); Set<String> set = convertListToSet(list); System.out.println("The converted Set: " + set); } } |
Output
Our List: [Mangoes, Oranges, Apples, Kiwi, Citrus, lemon] The converted Set: [Apples, Citrus, lemon, Kiwi, Mangoes, Oranges] |
Conclusion
To conclude, we have examined two ways to turn a List in Java into a Set. You may choose to use either approach according to your needs.
Keyword: Convert List to a set
Article Contributed By :
|
|
|
|
308 Views |