In this post, we will learn java array to set conversion.
[toc]
There are many ways to convert array to set.
1. Using Java 8’s Stream
If you are using Java 8, I would recommend using Java 8 Stream.
package org.arpit.java2blog;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
public class ArrayToSetMain {
public static void main(String[] args) {
String s[]= {"John","Martin","Mary","John","Martin"};
Set<String> set = Arrays.stream(s).collect(Collectors.toSet());
System.out.println(set);
}
}
Output
[John, Martin, Mary]
2. Using HashSet constructor()
We can directly call HashSet‘s constructor for java set to array conversion.
package org.arpit.java2blog;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class ArrayToSetMain {
public static void main(String[] args) {
String s[]= {"John","Martin","Mary","John","Martin"};
Set<String> set = new HashSet<>(Arrays.asList(s));;
System.out.println(set);
}
}
Output
[John, Martin, Mary]
3. Using Google Guava()
We can use google guava library to do Array to Set conversion using Sets’s newHashSet method.
package org.arpit.java2blog;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.compress.utils.Sets;
public class ArrayToSetMain {
public static void main(String[] args) {
String s[]= {"John","Martin","Mary","John","Martin"};
Set<String> set = Sets.newHashSet(s);
System.out.println(set);
}
}
Output
[John, Martin, Mary]
That’s all about Java Array to set conversion.