我想在Java中将数组转换为Set。有一些明显的方法可以做到这一点(即使用循环),但我想做一些更整洁的事情,比如:
java.util.Arrays.asList(Object[] a);
有什么想法吗?
我想在Java中将数组转换为Set。有一些明显的方法可以做到这一点(即使用循环),但我想做一些更整洁的事情,比如:
java.util.Arrays.asList(Object[] a);
有什么想法吗?
当前回答
我根据上面的建议写了下面的内容——偷吧……真不错!
/**
* Handy conversion to set
*/
public class SetUtil {
/**
* Convert some items to a set
* @param items items
* @param <T> works on any type
* @return a hash set of the input items
*/
public static <T> Set<T> asSet(T ... items) {
return Stream.of(items).collect(Collectors.toSet());
}
}
其他回答
使用stanford-stagger-3.0.jar中的CollectionUtils或ArrayUtils
import static edu.stanford.nlp.util.ArrayUtils.asSet;
or
import static edu.stanford.nlp.util.CollectionUtils.asSet;
...
String [] array = {"1", "q"};
Set<String> trackIds = asSet(array);
在Java 10中:
String[] strs = {"A", "B"};
Set<String> set = Set.copyOf(Arrays.asList(strs));
Set.copyOf返回包含给定集合元素的不可修改集合。
给定的集合不能为null,并且不能包含任何null元素。
private Map<Integer, Set<Integer>> nobreaks = new HashMap();
nobreaks.put(1, new HashSet(Arrays.asList(new int[]{2, 4, 5})));
System.out.println("expected size is 3: " +nobreaks.get(1).size());
输出为
expected size is 3: 1
将其更改为
nobreaks.put(1, new HashSet(Arrays.asList( 2, 4, 5 )));
输出为
expected size is 3: 3
在Eclipse集合中,以下功能将起作用:
Set<Integer> set1 = Sets.mutable.of(1, 2, 3, 4, 5);
Set<Integer> set2 = Sets.mutable.of(new Integer[]{1, 2, 3, 4, 5});
MutableSet<Integer> mutableSet = Sets.mutable.of(1, 2, 3, 4, 5);
ImmutableSet<Integer> immutableSet = Sets.immutable.of(1, 2, 3, 4, 5);
Set<Integer> unmodifiableSet = Sets.mutable.of(1, 2, 3, 4, 5).asUnmodifiable();
Set<Integer> synchronizedSet = Sets.mutable.of(1, 2, 3, 4, 5).asSynchronized();
ImmutableSet<Integer> immutableSet = Sets.mutable.of(1, 2, 3, 4, 5).toImmutable();
注意:我是Eclipse集合的提交人
快速:您可以做到:
// Fixed-size list
List list = Arrays.asList(array);
// Growable list
list = new LinkedList(Arrays.asList(array));
// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));
并反转
// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);
// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);