convert-list-to-set-and-set-to-list
Converting Between a List and a Set in Java
1. Overview
In this short article we will take a look at the conversion between a List and a Set – starting With Plain Java, using Guava and finally using the Apache Commons Collections library.
This article is part of the “Java – Back to Basic” series here on Baeldung.
Further reading:
How to Find an Element in a List with Java
Have a look at some quick ways to find an element in a list in Java
Check If Two Lists are Equal in Java
A short article focused on the common problem of testing if two List instances contain the same elements in exactly the same order.
2. Convert List to Set
public void givenUsingCoreJava_whenListConvertedToSet_thenCorrect() {
List<Integer> sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = new HashSet<>(sourceList);
}
As you can see, the conversion process is type-safe and very simple – since the constructors of each collection do accept another collection as a source.
2.2. With Guava
public void givenUsingGuava_whenListConvertedToSet_thenCorrect() {
List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = Sets.newHashSet(sourceList);
}
2.3. With Apache Commons Collections
public void givenUsingCommonsCollections_whenListConvertedToSet_thenCorrect() {
List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = new HashSet<>(6);
CollectionUtils.addAll(targetSet, sourceList);
}
3. Convert Set to List
public void givenUsingCoreJava_whenSetConvertedToList_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = new ArrayList<>(sourceSet);
}
3.2. With Guava
public void givenUsingGuava_whenSetConvertedToList_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = Lists.newArrayList(sourceSet);
}
Very similar to the java approach, only with a little less duplicated code.
3.3. With Apache Commons Collections
public void givenUsingCommonsCollections_whenSetConvertedToList_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = new ArrayList<>(6);
CollectionUtils.addAll(targetList, sourceSet);
}
4. Conclusion
The implementation of all these examples and code snippets can be found over on GitHub – this is a Maven-based project, so it should be easy to import and run as it is.