Java中列表和集合的转换
Contents
1. 概述
在这个快速教程中,我们将了解List和Set之间的转换**,从普通 Java 开始,使用 Guava 和Apache Commons Collections 库,最后使用 Java 10。
2. 将List转换为Set
2.1. 使用纯 Java
让我们从使用 Java将List转换为Set开始:
public void givenUsingCoreJava_whenListConvertedToSet_thenCorrect() {
List<Integer> sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = new HashSet<>(sourceList);
}
正如我们所见,转换过程是类型安全且直接的,因为每个集合的构造函数都接受另一个集合作为源。
2.2. 使用 Guava
让我们使用 Guava 进行相同的转换:
public void givenUsingGuava_whenListConvertedToSet_thenCorrect() {
List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = Sets.newHashSet(sourceList);
}
2.3. 使用 Apache Commons Collections
接下来让我们使用 Commons Collections API 在List和Set之间进行转换:
public void givenUsingCommonsCollections_whenListConvertedToSet_thenCorrect() {
List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = new HashSet<>(6);
CollectionUtils.addAll(targetSet, sourceList);
}
2.4. 使用 Java 10
另一种选择是使用 Java 10 中引入的 Set.copyOf 静态工厂方法:
public void givenUsingJava10_whenListConvertedToSet_thenCorrect() {
List sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
Set targetSet = Set.copyOf(sourceList);
}
请注意,以这种方式创建的Set是不可修改 的。
3. 将Set转换为List
3.1. 使用纯 Java
现在让我们使用 Java进行反向转换,从Set到List:
public void givenUsingCoreJava_whenSetConvertedToList_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = new ArrayList<>(sourceSet);
}
3.2. 使用 Guava
我们可以使用 Guava 解决方案来做同样的事情:
public void givenUsingGuava_whenSetConvertedToList_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = Lists.newArrayList(sourceSet);
}
这与 java 方法非常相似,只是重复的代码少了一点。
3.3. 使用 Apache Commons Collections
现在让我们看看在Set和List之间转换的 Commons Collections 解决方案:
public void givenUsingCommonsCollections_whenSetConvertedToList_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = new ArrayList<>(6);
CollectionUtils.addAll(targetList, sourceSet);
}
3.4. 使用 Java 10
最后,我们可以使用 Java 10 中引入的List.copyOf :
public void givenUsingJava10_whenSetConvertedToList_thenCorrect() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = List.copyOf(sourceSet);
}
我们需要记住,生成的List是不可修改 的。