This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

How do I initialize a HashSet value by constructing it?

I need Set to create one using the initial value.

Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
Copy the code

Is there a way to do that in one line of code? For example, it is useful for final static fields

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}

If you’re looking for the most compact way to initialize a collection, it’s in Java9:

Set<String> strSet = Set.of("Apple", "Ball", "Cat", "Dog");
Copy the code

= = = = = = = = = = = = = = = = = = = = = the following detailed answer = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 10 (immutable) using Java

Set<String> strSet1 = Stream.of("A", "B", "C", "D")
         .collect(Collectors.toUnmodifiableSet());
Copy the code

It is clear from the statement in the set -> (set) set.of (set.toarray ()) source code that the collector will actually return the immutable collections introduced in Java 9.

To note is that the method Collections. UnmodifiableSet () returns the specified set of immutable view (according to the document). A collection of modified views is a collection, is immutable, and is also a graph-to-backing collection. Note that changes to the backing collection may still be possible, and if they occur, they are visible by modifying the view. But this method Collectors. ToUnmodifiableSet () returns the Java 10 real constant set. Using Java 9 (Immutable Sets)

Here is the most compact way to initialize a collection:

Set<String> strSet6 = Set.of("Apple", "Ball", "Cat", "Dog");
Copy the code

We have 12 overloaded versions of this convenience factory method:

static <E> Set<E> of() static <E> Set<E> of(E e1) static <E> Set<E> of(E e1, E e2) // .... Static <E> Set<E> of(E... elems)Copy the code

So the natural question is, why do we need to reload when we have var-args? The answer is: each var-arg method creates an array internally, and the overloaded version will avoid unnecessary object creation and will also save us from the overhead of garbage collection. Using Java 8 (Modifiable set)

Use Stream in Java 8.

Set<String> strSet1 = Stream.of("A", "B", "C", "D")
         .collect(Collectors.toCollection(HashSet::new));

// stream from an array (String[] stringArray)
Set<String> strSet2 = Arrays.stream(stringArray)
         .collect(Collectors.toCollection(HashSet::new));

// stream from a list (List<String> stringList)
Set<String> strSet3 = stringList.stream()
         .collect(Collectors.toCollection(HashSet::new));
Copy the code

Using Java 8 (immutable) use Collections. UnmodifiableSet ()

We can Collections. UnmodifiableSet () is used as:

Set<String> strSet4 = Collections.unmodifiableSet(strSet1);
Copy the code

But it looks a little awkward, so we can write our own collector like this:

class ImmutableCollector { public static <T> Collector<T, Set<T>, Set<T>> toImmutableSet() { return Collector.of(HashSet::new, Set::add, (l, r) -> { l.addAll(r); return l; }, Collections::unmodifiablSet); }}Copy the code

Then use it as:

Set<String> strSet4 = Stream.of("A", "B", "C", "D")
             .collect(ImmutableCollector.toImmutableSet());

Copy the code

# # # use Collectors. CollectingAndThen () another way is to use [Collectors. CollectingAndThen (a)] [6] method, this method allows us to perform additional finishing conversion:

import static java.util.stream.Collectors.*;
Set<String> strSet5 = Stream.of("A", "B", "C", "D").collect(collectingAndThen(
   toCollection(HashSet::new),Collections::unmodifiableSet));
Copy the code

If we only care about Set, then we can also use Collectors. ToSet () instead of Collectors. ToCollection (HashSet::new).

The article translated from am2dgbqfb6mk75jcyanzabc67y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 2…

Set strSet1 = stream.of (“A”, “B”, “C”, “D”).collect(Collectors. ToCollection (HashSet::new));


Welcome to my column S t a c k O v e r F l o w . I select the best questions and answers and test them frequently in interviews ! ! !   \color{red} Welcome to my column StackOverFlow, I will filter the quality of the interview test!! {~}


There are the latest and elegant ways to do this, and I will write my thoughts on this q&A at the end of the article \color{red} has the latest, elegant implementation, and I will also write my opinion on this question at the end of the article {~}

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️