Is...">

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 ?

+58
java collections
May 03 '13 at 12:20
source share
8 answers

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!

+9
Dec 23 '16 at 16:46
source share

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.

+47
May 03 '13 at 12:24
source share

you can use

 new HashSet<String>(Arrays.asList("a","b")); 
+33
May 03 '13 at 12:21
source share

For special cases of sets with zero or one member, you can use:

 java.util.Collections.EMPTY_SET 

and

 java.util.Collections.singleton("A") 
+16
Jan 15 '15 at 16:20
source share

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.

+14
May 03 '13 at 12:28
source share

No, but you can do it like this

 new HashSet<String>(Arrays.asList("a", "b", ...)); 
+2
May 3 '13 at 12:22
source share

In guava you can use

 Set<String> set = Sets.newHashSet("a","b","c"); 

newHashSet

+2
May 03 '13 at 12:27
source share

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)); } 
0
Oct 03 '17 at 10:38 on
source share



All Articles