假设以下是带有字符串值的列表-
List<String> list = Arrays.asList("Jacob", "Kiya", "Bradley", "Tom", "Jamie");
现在,将上面的列表转换为set-
Set<String> set = new HashSet<String>(list);
以下是在Java中将List转换为Set的程序-
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]