What is immutable map in java

Tech Tutorials

Tutorials and posts about Java, Spring, Hadoop and many more. Java code examples and interview questions. Spring code examples.

Saturday, July 16, 2022

Unmodifiable or Immutable Map in Java

An unmodifiable Map in Java is one whose keys and values cannot be added, removed, or updated once the unmodifiable instance of a Map is created. In this post we’ll see how Unmodifiable Map was created before Java 9 and how it can be created Java 9 onward using Immutable Map Static Factory Methods.

Creating Unmodifiable Map before Java 9

Till Java 8 in order to create unmodifiable Map Collections.unmodifiableMap() method was used.

Collections.unmodifiableMap(Map m)— Returns an unmodifiable view of the specified map. Attempt to modify the returned map, whether direct or via its collection views, result in an UnsupportedOperationException.

Drawback of this method is that the underlying Map is still modifiable let’s try to see it with an example.

public class UnmodifiableMap < public static void main(String[] args) < MapalphaMap = new HashMap(); alphaMap.put("1", "a"); alphaMap.put("2", "b"); alphaMap.put("3", "c"); alphaMap.put("4", "d"); Map aMap = Collections.unmodifiableMap(alphaMap); // still mutable alphaMap.put("5", "e"); System.out.println("alphaMap- " + alphaMap); //error as this Map is an unmodifiable view aMap.put("6", "f"); > >
alphaMap- Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.Collections$UnmodifiableMap.put(Collections.java:1455) at org.netjs.Programs.UnmodifiableMap.main(UnmodifiableMap.java:20)

As you can see original map alphaMap can still be modified, though the unmodifiable Map view can’t be modified.

Читайте также:  Python isdecimal isdigit isnumeric

Creating Unmodifiable Map in Java 9

The Map.of (Java 9), Map.ofEntries (Java 9), and Map.copyOf (Java 10) static factory methods provide a convenient way to create unmodifiable maps. The Map instances created by these methods have the following characteristics:

  1. They are unmodifiable. Keys and values cannot be added, removed, or updated. Calling any mutator method results in UnsupportedOperationException to be thrown. However, if the contained keys or values are themselves mutable, this may cause the Map to behave inconsistently or its contents to appear to change.
  2. Immutable maps don’t allow null keys and values. Attempts to create them with null keys or values result in NullPointerException.
  3. Duplicate keys are rejected at creation time itslef. Passing duplicate keys to a static factory method result in IllegalArgumentException.
  4. Immutable maps are serializable if all keys and values are serializable.
  5. The iteration order of mappings is unspecified and is subject to change.

Java Map.of() methods for creating unmodifiable Map

Map.of() static factory method is a convenient way to create unmodifiable maps Java 9 onward. This method is overloaded to have up to 10 elements and the form of the method is as follows.

Map.of()- Returns an unmodifiable map containing zero mappings. Map.of(K k1, V v1)- Returns an unmodifiable map containing a single mapping. .. .. Map.of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9)- Returns an unmodifiable map containing nine mappings. Map.of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10)- Returns an unmodifiable map containing ten mappings.

Map.of() method Java example

public class UnmodifiableMap < public static void main(String[] args) < MapalphaMap = Map.of("1","a", "2","b", "3","c", "4","d"); System.out.println("alphaMap- " + alphaMap); // Error alphaMap.put("5", "e"); > >
alphaMap- Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:72) at java.base/java.util.ImmutableCollections$AbstractImmutableMap.put(ImmutableCollections.java:731) at org.netjs.Programs.UnmodifiableMap.main(UnmodifiableMap.java:13)

As you can see trying to modify the immutable Map results in UnsupportedOperationException.

Java Map.ofEntries() method for creating unmodifiable Map

  • Map.ofEntries(Map.Entry. entries)— Returns an unmodifiable map containing keys and values extracted from the given entries. The entries themselves are not stored in the map.
import java.util.Map; import static java.util.Map.entry; public class UnmodifiableMap < public static void main(String[] args) < MapalphaMap = Map.ofEntries(entry("1", "a"), entry("2", "b"), entry("3", "c"), entry("4", "d")); System.out.println("alphaMap- " + alphaMap); > >

Map.copyOf() method in Java

  • Map.copyOf(Map map)— Returns an unmodifiable Map containing the entries of the given Map. The given Map must not be null, and it must not contain any null keys or values. If the given Map is subsequently modified, the returned Map will not reflect such modifications.
public class UnmodifiableMap < public static void main(String[] args) < MapalphaMap = new HashMap(); alphaMap.put("1", "a"); alphaMap.put("2", "b"); alphaMap.put("3", "c"); alphaMap.put("4", "d"); Map aMap = Map.copyOf(alphaMap); System.out.println(" aMap- " + aMap); > >

That’s all for this topic Unmodifiable or Immutable Map in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Источник

Неизменяемая карта в Java (с использованием Guava и Java 9)

В этом посте будут обсуждаться различные методы создания неизменяемой карты в Java.

Неизменяемые карты являются обертками “только для чтения” над другими коллекциями. Они не поддерживают никаких операций модификации, таких как добавление, удаление и очистка, но их базовую коллекцию можно изменить. Карты, которые дополнительно гарантируют, что никакие изменения в объекте Collection никогда не будут видны, называются неизменяемыми картами.

Если вы не собираетесь изменять коллекцию, хорошей практикой будет копирование ее в неизменяемую коллекцию. Неизменяемые карты имеют много преимуществ перед своими изменяемыми братьями и сестрами, например, они потокобезопасны, более эффективно используют память и могут быть переданы в ненадежные библиотеки без каких-либо побочных эффектов.

1. Использование библиотеки Guava

Платформа коллекций Java обеспечивает unmodifiableMap() метод, но его небезопасно использовать, так как возвращенная карта действительно неизменяема только в том случае, если ни у кого нет ссылки на исходную коллекцию. Возвращаемая карта также неэффективна, поскольку структуры данных по-прежнему будут иметь все накладные расходы изменяемых коллекций, включая одновременные проверки модификации, дополнительное пространство в хеш-таблицах и т. д.

Guava предоставляет простые, легкие в использовании неизменяемые версии каждой карты, используя ImmutableMap учебный класс. В отличие от коллекций unmodifiableMap() , экземпляр ImmutableMap содержит свои собственные личные данные и никогда не изменится. Мы можем создать ImmutableMap сбор несколькими способами:

⮚ Использование copyOf() метод

ImmutableMap.copyOf возвращает неизменяемую карту, содержащую те же записи, что и указанная карта. Он возвращает NullPointerException если какой-либо ключ или значение на карте имеет значение null.

Источник

How to create immutable Map in Java

In this tutorial, we will see how we can create an immutable Map in Java.

– What does it mean by immutable class or object?

– How to create an immutable Map in java?

What does it mean by immutable class or object?

An immutable class or object is a class or object whose state does not change once it is created.For example String class in Java is immutable, such that if we try to make changes in our String object ,it will create a new String object but state of current object will not change.So if we instantiate an immutable class, we can not change the state of that instance, once it is created.

What is an Immutable Map?

So considering the above definition of immutable, an immutable map is a map in which we can not insert, update or delete elements once it is created.This kind of Map will usually be required to have content which is not expected to be changed like country and it’s currency.

How to create an immutable Map in java?

There are various ways in which we can create an Immutable Map.

Using Collections.unmodifiableMap()

Example 1

When we use Collections.unmodifiableMap(originalMap),it creates a view over our original map, such that we can not add, delete or update on this view and if we try ,we get UnSupportedOperation exception, but we can just view the data which is there in the original map.

We can still update the original map and as we change original Map ,changes will be reflected in the view as well. so this does not in true sense creates immutable map.However we can still create immutable map using Collections.unmodifiableMap(). For that check second example.

Map originalMap1 = new HashMap(); originalMap1.put("a", 1); originalMap1.put("b", 2); originalMap1.put("c", 3); Map unmodifiableMap1 = Collections.unmodifiableMap(originalMap1); //unmodifiableMap1.put("d", 4); System.out.println("Size of originalMap1 before adding new data:"+originalMap1.size()); System.out.println("Size of unmodifiableMap1 before adding new data:"+ unmodifiableMap1.size()); originalMap1.put("e", 5); System.out.println("Size of originalMap1 after adding new data:"+originalMap1.size()); System.out.println("Size of unmodifiableMap1 after adding new data:"+unmodifiableMap1.size());

Example 2

Map originalMap2 = new HashMap(); originalMap2.put("a", 1); originalMap2.put("b", 2); originalMap2.put("c", 3); Map unmodifiableMap2 = Collections.unmodifiableMap(new HashMap(originalMap2)); //unmodifiableMap2.put("d", 4); System.out.println("Size of originalMap2 before adding new data:"+originalMap2.size()); System.out.println("Size of unmodifiableMap2 before adding new data:"+ unmodifiableMap2.size()); originalMap2.put("e", 5); System.out.println("Size of originalMap2 after adding new data:"+originalMap2.size()); System.out.println("Size of unmodifiableMap2 after adding new data:"+unmodifiableMap2.size());

Here instead of passing reference to the original map, we create a new instance of HashMap, passing it original hashMap and then pass this new instance of HashMap to Collecitons.unmodifiableMap() method.The “unmodifiableMap2” that we get here is immutable such that even if you make changes in the original hashmap, it will not reflect in the unmodifiableMap2 instance.

Using Map.of()

Map.of() was introduced in Java 9.Following example is self explanatory.This method should be used if we have less than equal to 10 key value pairs, because if we see the overloads of Of() method, there are maximum 10 key value pairs allowed in the overload of Of() method.

static Map of() static Map of(K k1, V v1) static Map of(K k1, V v1, K k2, V v2) . . . static Map of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10)

Example

Map immutableMap1 = Map.of("a", 1, "b",2, "c",3); //immutableMap1.put("d", 4); //Will throw UnsupportedOperaironException System.out.println("Size of immutableMap1:"+ immutableMap1.size());

Using Map.ofEntries()

Map.ofEntries() was also introduced in Java 9.We can use this method of creating immutable map when we have more than 10 key value pairs.

Signature of this method is as below :

static Map ofEntries(Entry. entries)

Example

Map immutableMap2 = Map.ofEntries( entry("a",1), entry("b",2), entry("c",3)); //immutableMap2.put("d", 4); System.out.println("Size of immutableMap2 :"+immutableMap2.size());

Using Map.copyOf()

Map.copyOf() was introduced in Java 10.

Signature of this method is as below :

Example

Map originalMap5 = new HashMap(); originalMap5.put("a", 1); originalMap5.put("b", 2); originalMap5.put("c", 3); Map immutableMap3 = Map.copyOf(originalMap5); //immutableMap3.put("d", 4); System.out.println("Size of originalMap5 before adding new data:"+originalMap5.size()); originalMap5.put("e", 5); System.out.println("Size of originalMap5 after adding new data:"+originalMap5.size()); System.out.println("Size of immutableMap3 after adding new data:"+immutableMap3.size());

Complete code with all above examples

package com.blogspot.javasolutionsguide.immutable_map_java_example; import static java.util.Map.entry; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * ImmutableMapTest. * */ public class ImmutableMapTest < public static void main( String[] args ) < //Unmodifiable MaporiginalMap1 = new HashMap(); originalMap1.put("a", 1); originalMap1.put("b", 2); originalMap1.put("c", 3); Map unmodifiableMap1 = Collections.unmodifiableMap(originalMap1); //unmodifiableMap1.put("d", 4); System.out.println("Size of originalMap1 before adding new data:"+originalMap1.size()); originalMap1.put("e", 5); System.out.println("Size of originalMap1 after adding new data:"+originalMap1.size()); System.out.println("Size of unmodifiableMap1 after adding new data:"+unmodifiableMap1.size()); //Example 2 Map originalMap2 = new HashMap(); originalMap2.put("a", 1); originalMap2.put("b", 2); originalMap2.put("c", 3); Map unmodifiableMap2 = Collections.unmodifiableMap(new HashMap(originalMap2)); //unmodifiableMap2.put("d", 4); System.out.println("Size of originalMap2 before adding new data:"+originalMap2.size()); originalMap2.put("e", 5); System.out.println("Size of originalMap2 after adding new data:"+originalMap2.size()); System.out.println("Size of unmodifiableMap2 after adding new data:"+unmodifiableMap2.size()); //Example 3 Map immutableMap1 = Map.of("a", 1, "b",2, "c",3); //immutableMap1.put("d", 4); //Will throw UnsupportedOperaironException System.out.println("Size of immutableMap1:"+ immutableMap1.size()); //Example 4 Map immutableMap2 = Map.ofEntries( entry("a",1), entry("b",2), entry("c",3)); //immutableMap2.put("d", 4); System.out.println("Size of immutableMap2 :"+immutableMap2.size()); //Example 5 Map originalMap5 = new HashMap(); originalMap5.put("a", 1); originalMap5.put("b", 2); originalMap5.put("c", 3); Map immutableMap3 = Map.copyOf(originalMap5); //immutableMap3.put("d", 4); System.out.println("Size of originalMap5 before adding new data:"+originalMap5.size()); originalMap5.put("e", 5); System.out.println("Size of originalMap5 after adding new data:"+originalMap5.size()); System.out.println("Size of immutableMap3 after adding new data:"+immutableMap3.size()); > >

Summary :

So ,in this tutorial, we saw how we can create immutable map in Java.This is really useful when we know that content of our map is not going to change in future.We saw how JDK has various methods to create immutable maps.

Thanks for reading. Subscribe to our blog for more such interesting posts.

Published on Java Code Geeks with permission by Gaurav Bhardwaj, partner at our JCG program. See the original article here: How to create immutabe Map in Java

Источник

Оцените статью