在 Java 中将列表转换为集合

java 8object oriented programmingprogramming

假设以下是带有字符串值 − 的列表

List<String> list = Arrays.asList("Jacob", "Kiya", "Bradley", "Tom", "Jamie");

现在,将上述列表转换为集合 −

Set<String> set = new HashSet<String>(list);

示例

以下是在 Java 中将列表转换为集合的程序 −

import java.util.*;
import java.util.stream.*;
public class Demo {
   public static void main(String args[]) {
      List<String> list = Arrays.asList("Jacob", "Kiya", "Bradley", "Tom", "Jamie");
      System.out.println("List = " + list);
      Set<String> set = new HashSet<String>(list);
      System.out.println("Set (converted from list) = " + set);
   }
}

输出

List = [Jacob, Kiya, Bradley, Tom, Jamie]
Set (converted from list) = [Jamie, Tom, Bradley, Kiya, Jacob]

相关文章