Java 可以将List转换为Set然后再转回吗
可以使用Set构造函数将列表转换为set对象。所得到的set将消除列表中的任何重复条目,只包含唯一的值。
Set<String> set = new HashSet<>(list);
按类似的模式,我们可以使用其构造函数从集合中获取列表。
List<Integer> list = new ArrayList<Integer>(set);
示例
以下是将列表转换为集合和将集合转换为列表的示例:
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class CollectionsDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,3,3,4,5));
System.out.println("List: " + list);
Set<Integer> set = new HashSet<>(list);
System.out.println("Set: " + set);
List<Integer> list1 = new ArrayList<Integer>(set);
System.out.println("List: " + list1);
}
}
输出
这将产生以下结果:
List: [1, 2, 3, 3, 3, 4, 5]
Set: [1, 2, 3, 4, 5]
List: [1, 2, 3, 4, 5]