package com.sheting.basic.collection.list;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections4.CollectionUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
public class ConvertListToSetAndSetToList {
public static void main(String[] args) {
convertListToSet_1();
convertSetToList_1();
convertListToSet_2();
convertSetToList_2();
convertListToSet_3();
convertSetToList_3();
}
// ****With plain Java
public static void convertListToSet_1() {
List<Integer> sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = new HashSet<>(sourceList);
}
public static void convertSetToList_1() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = new ArrayList<>(sourceSet);
}
// ****With Guava
public static void convertListToSet_2() {
List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = Sets.newHashSet(sourceList);
}
public static void convertSetToList_2() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = Lists.newArrayList(sourceSet);
}
// ****With Apache Commons Collections
public static void convertListToSet_3() {
List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
Set<Integer> targetSet = new HashSet<>(6);
CollectionUtils.addAll(targetSet, sourceList);
}
public static void convertSetToList_3() {
Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
List<Integer> targetList = new ArrayList<>(6);
CollectionUtils.addAll(targetList, sourceSet);
}
}
Converting between a List and a Set in Java
最新推荐文章于 2023-12-22 02:23:09 发布