📜  在Java中设置的列表

📅  最后修改于: 2022-05-13 01:55:15.357000             🧑  作者: Mango

在Java中设置的列表

给定一个列表(ArrayList 或 LinkedList),将其转换为Java中字符串的集合(HashSet 或 TreeSet)。

方法1(简单)
我们只需创建一个列表。我们遍历给定的集合,并将元素一个一个地添加到列表中。

// 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 aList = Arrays.asList("Geeks", "for",
                     "GeeksQuiz", "GeeksforGeeks", "GFG");
  
        Set hSet = new HashSet();
        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
    }
}

方法2(使用HashSet或TreeSet构造函数)

// 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 aList = Arrays.asList("Geeks", "for",
                     "GeeksQuiz", "GeeksforGeeks", "GFG");
  
        // Creating a hash set using constructor
        Set hSet = new HashSet(aList);
  
        System.out.println("Created HashSet is");
        for (String x : hSet)
            System.out.println(x);
  
        System.out.println("Created TreeSet is");
        Set tSet = new TreeSet(aList);
        System.out.println("Created TreeSet is");
        for (String x : tSet)
            System.out.println(x);
    }
}

方法 3(使用 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 aList = Arrays.asList("Geeks", "for",
                    "GeeksQuiz", "GeeksforGeeks", "GFG");
  
        Set hSet = new HashSet(aList);
        hSet.addAll(aList);
        System.out.println("Created HashSet is");
        for (String x : hSet)
            System.out.println(x);
  
        Set tSet = new TreeSet(aList);
        tSet.addAll(aList);
        System.out.println("Created TreeSet is");
        for (String x : tSet)
            System.out.println(x);
    }
}

方法4(在Java中使用流)
我们在Java中使用流将给定的列表转换为流,然后将流转换为集合。这仅适用于Java 8 或之后的版本。

// 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 aList = Arrays.asList("Geeks", "for",
                    "GeeksQuiz", "GeeksforGeeks", "GFG");
  
        // Converting to set using stream
        Set set = aList.stream().collect(Collectors.toSet());
  
        for (String x : set)
            System.out.println(x);
    }
}