From 8ce227cce7d92ca7ac1e5e7b0e63b8b41da604a2 Mon Sep 17 00:00:00 2001 From: mherbaghinyan Date: Fri, 28 Dec 2018 16:26:57 +0400 Subject: [PATCH] immutable sets --- .../com/baeldung/set/UnmodifiableSet.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 core-java-collections/src/main/java/com/baeldung/set/UnmodifiableSet.java diff --git a/core-java-collections/src/main/java/com/baeldung/set/UnmodifiableSet.java b/core-java-collections/src/main/java/com/baeldung/set/UnmodifiableSet.java new file mode 100644 index 0000000000..d821c46a3c --- /dev/null +++ b/core-java-collections/src/main/java/com/baeldung/set/UnmodifiableSet.java @@ -0,0 +1,44 @@ +package com.baeldung.set; + +import com.google.common.collect.ImmutableSet; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +public class UnmodifiableSet { + + public static void main(String[] args) { + + Set set = new HashSet<>(); + set.add("Canada"); + set.add("USA"); + + coreJDK(set); + guavaOf(); + copyOf(set); + setOf(); + } + + private static void setOf() { + Set immutable = Set.of("Canada", "USA"); + System.out.println(immutable); + } + + private static void guavaOf() { + Set immutable = ImmutableSet.of("Canada", "USA"); + System.out.println(immutable); + } + + private static void copyOf(Set set) { + Set immutable = ImmutableSet.copyOf(set); + set.add("Costa Rica"); + System.out.println(immutable); + } + + private static void coreJDK(Set set) { + Set unmodifiableSet = Collections.unmodifiableSet(set); + set.add("Costa Rica"); + System.out.println(unmodifiableSet); + } +}