
We can use Collections.unmodifiableSet() as: Set strSet4 = Collections. Using Java 8 (Unmodifiable Sets) Using Collections.unmodifiableSet() stream from an array (String stringArray) collect(Collectors.toCollection(HashSet::new)) Then a natural question is why we need overloaded versions when we have var-args? The answer is: every var-arg method creates an array internally and having the overloaded versions would avoid unnecessary creation of object and will also save us from the garbage collection overhead. We have 12 overloaded versions of this convenience factory method:
Initialize a hashmap java how to#
The following is the most compact way of initializing a set: Set strSet6 = Set.of("Apple", "Ball", "Cat", "Dog") Java 8- Lambda expression and streams to iterate over HashMap of HashMap 1 How to initialise in Java a Map
But the method Collectors.toUnmodifiableSet() returns truly immutable set in Java 10. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. One point to note is that the method Collections.unmodifiableSet() returns an unmodifiable view of the specified set (as per documentation). Here the collector would actually return the unmodifiable set introduced in Java 9 as evident from the statement set -> (Set)Set.of(set.toArray()) in the source code. collect(Collectors.toUnmodifiableSet()) = Detailed answer below = Using Java 10 (Unmodifiable Sets) Set strSet1 = Stream.of("A", "B", "C", "D")

If you are looking for the most compact way of initializing a set then that was in Java9: Set strSet = Set.of("Apple", "Ball", "Cat", "Dog")
