In this post, we will learn java array to set conversion.
1. Using Java 8’s Stream
If you are using Java 8, I would recommend using Java 8 Stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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
2. Using HashSet constructor()
We can directly call HashSet‘s constructor for java set to array conversion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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
3. Using Google Guava()
We can use google guava library to do Array to Set conversion using Sets’s newHashSet method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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
That’s all about Java Array to set conversion.