由于List和Set不同的存取特性,比如Set中元素不重复、List根据索引随机访问元素等,在一些特定的场景下需要根据不同的需求将List和Set进行相互转换。
1.List转Set
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
// 使用 HashSet 的构造函数将List转换为Set
Set<Integer> set = new HashSet<>(list);
2.Set转List
Set<Integer> set = new HashSet<>();
// 使用 ArrayList 的构造函数将Set转换为List
List<Integer> list = new ArrayList<>(set);