Dada una lista ( ArrayList o LinkedList ), conviértala en un conjunto ( HashSet o TreeSet ) de strings en Java.
Método 1 (Simple)
Simplemente creamos una lista. Recorremos el conjunto dado y uno por uno agregamos elementos a la lista.
// Java program to demonstrate conversion of // list to set using simple traversal import java.util.*; class Test { public static void main(String[] args) { // Creating a list of strings List<String> aList = Arrays.asList("Geeks", "for", "GeeksQuiz", "GeeksforGeeks", "GFG"); Set<String> hSet = new HashSet<String>(); for (String x : aList) hSet.add(x); System.out.println("Created HashSet is"); for (String x : hSet) System.out.println(x); // We can created TreeSet same way } }
Método 2 (usando HashSet o TreeSet Constructor)
// Java program to demonstrate conversion of // list to set using constructor import java.util.*; class Test { public static void main(String[] args) { // Creating a list of strings List<String> aList = Arrays.asList("Geeks", "for", "GeeksQuiz", "GeeksforGeeks", "GFG"); // Creating a hash set using constructor Set<String> hSet = new HashSet<String>(aList); System.out.println("Created HashSet is"); for (String x : hSet) System.out.println(x); System.out.println("Created TreeSet is"); Set<String> tSet = new TreeSet<String>(aList); System.out.println("Created TreeSet is"); for (String x : tSet) System.out.println(x); } }
Método 3 (usando el método addAll)
// Java program to demonstrate conversion of // Set to array using addAll() method. import java.util.*; class Test { public static void main(String[] args) { // Creating a list of strings List<String> aList = Arrays.asList("Geeks", "for", "GeeksQuiz", "GeeksforGeeks", "GFG"); Set<String> hSet = new HashSet<String>(aList); hSet.addAll(aList); System.out.println("Created HashSet is"); for (String x : hSet) System.out.println(x); Set<String> tSet = new TreeSet<String>(aList); tSet.addAll(aList); System.out.println("Created TreeSet is"); for (String x : tSet) System.out.println(x); } }
Método 4 (Uso de flujo en Java )
Usamos flujo en Java para convertir una lista dada en flujo, luego flujo en conjunto. Esto funciona solo en Java 8 o versiones posteriores.
// Java program to demonstrate conversion of // Set to list using stream import java.util.*; import java.util.stream.*; class Test { public static void main(String[] args) { // Creating a list of strings List<String> aList = Arrays.asList("Geeks", "for", "GeeksQuiz", "GeeksforGeeks", "GFG"); // Converting to set using stream Set<String> set = aList.stream().collect(Collectors.toSet()); for (String x : set) System.out.println(x); } }