I'm looking for a very simple way to create a Set.
Arrays.asList("a", "b" ...)
creates a List<String>
Is there anything similar for Set
?
I'm looking for a very simple way to create a Set.
Arrays.asList("a", "b" ...)
creates a List<String>
Is there anything similar for Set
?
Now with Java 8 you can do this without need of third-party framework:
Set<String> set = Stream.of("a","b","c").collect(Collectors.toSet());
See Collectors.
Enjoy!
Using Guava, it is as simple as that:
Set<String> mySet = ImmutableSet.<String> of("a", "b");
Or for a mutable set:
Set<String> mySet = Sets.newHashSet("a", "b")
For more data types see the Guava user guide
You could use
new HashSet<String>(Arrays.asList("a","b"));
In Java 9, similar function has been added via factory methods:
Set<String> oneLinerSet = Set.of("a", "b", ...);
(There are equivalents for List
as well.)
For the special cases of sets with zero or one members, 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 that Arrays.asList
returns a fixed sized list, in other words:
public static void main(String a[])
{
List<String> myList = Arrays.asList("a", "b");
myList.add("c");
}
Returns:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
There is no JDK implementation of a "fixed-size" Set
inside the Arrays
class. Why do you want this? A Set
guarantees that there are no duplicates, but if you are typing them out by hand, you shouldn't need that 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's not in the JDK. Look at their answers (in particular Michael Schmeißer's answer) for information on that.
No but you can do it like this
new HashSet<String>(Arrays.asList("a", "b", ...));
Here's a little method 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));
}
Another way to do it using Java 8 and enums would be:
Set<String> set = EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.READ);
See EnumSet.
I would recommend a performance analysis between this approach and
Set<String> set = Stream.of(StandardOpenOption.CREATE, StandardOpenOption.READ).collect(Collectors.toSet());
because if you have more than five elements the javadoc of the method states that may be performance issues as you can see in the javadoc of Set.Of(E, E...).
List<String> myList = new ArrayList<String>(Arrays.asList("a", "b"));
myList.add("c");
System.out.println(myList);
It worked without error