Does .asSet (...) exist in any API?
I am looking for a very simple way to create a kit.
Arrays.asList("a", "b" ...) creates a List<String>
Is there something similar for Set ?
Now with Java 8, you can do this without the need for a third-party structure:
Set<String> set = Stream.of("a","b","c").collect(Collectors.toSet()); See Collectors .
Enjoy it!
Using Guava , it is so simple:
Set<String> mySet = ImmutableSet.<String> of("a", "b"); Or for mutable set:
Set<String> mySet = Sets.newHashSet("a", "b") See the Guava User Guide for more information.
you can use
new HashSet<String>(Arrays.asList("a","b")); For special cases of sets with zero or one member, you can use:
java.util.Collections.EMPTY_SET and
java.util.Collections.singleton("A") As others have said, use:
new HashSet<String>(Arrays.asList("a","b")); The reason this does not exist in Java is because Arrays.asList returns a list of a fixed size, in other words:
public static void main(String a[]) { List<String> myList = Arrays.asList("a", "b"); myList.add("c"); } Return:
Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.add(Unknown Source) at java.util.AbstractList.add(Unknown Source) The Arrays class lacks the implementation of the JDK "fixed size" Set . Why do you want this? A Set ensures that there are no duplicates, but if you print them manually, you do not need this functionality ... and List has more methods. Both interfaces extend Collection and Iterable .
As others have said, use guava if you really want this functionality since it is not in the JDK. See their answers (in particular, Michael Schmeisser's answer) for information on this.
No, but you can do it like this
new HashSet<String>(Arrays.asList("a", "b", ...)); Here is a small way you can use
/** * Utility method analogous to {@link java.util.Arrays#asList(Object[])} * * @param ts * @param <T> * @return the set of all the parameters given. */ @SafeVarargs @SuppressWarnings("varargs") public static <T> Set<T> asSet(T... ts) { return new HashSet<>(Arrays.asList(ts)); }