0

How to create checked Set with one (or more elements)

I have some Objects of type A and I want to create checked Set with all these objects

A element1; //not null
A element2; //not null; optional

my solution:

Set<A> s = new HashSet<>(1);
a.add(element1);
a.add(element2); //optional

Q: Is there any standard util class to create it in simple way?

Something like

   List<A> l = java.util.Arrays.asList(element1);
   List<A> l = java.util.Arrays.asList(element1, element2); // optional

but for Set

THM
  • 579
  • 6
  • 25

2 Answers2

0

In JDK-8:

Stream.of(element1, element2).collect(toSet());

or to guarantee the type of set returned:

Stream.of(element1, element2).collect(toCollection(HashSet::new));

if not on JDK8 yet then the best option is probably:

new HashSet<>(Arrays.asList(element1, element2));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0
Set<A> s = new HashSet<>(Arrays.asList(element1, element2));
Khalid Shah
  • 3,132
  • 3
  • 20
  • 39