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"));
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")
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With