Decrypting a Map in Java: How to efficiently manipulate key-value pairs?

Foreword

Map is one of the very important data structures in Java. It stores key-value pairs and can quickly find the corresponding value through the key. It is one of the most frequently used data structures in our actual development. This article aims to introduce common Map implementations in Java, their advantages and disadvantages, and how to efficiently operate key-value pairs in practical applications.

Abstract

This article first introduces common Map implementations in Java, including HashMap, TreeMap, LinkedHashMap and ConcurrentHashMap. Then their characteristics, advantages and disadvantages, and applicable scenarios are introduced respectively. Then it introduces how to use Map in practical applications, including how to add, delete, update and query key-value pairs. Finally, through actual code implementation, it demonstrates how to efficiently operate key-value pairs in Java.

Content

Common Map implementations

HashMap

HashMap is one of the most commonly used Map implementations in Java. It uses the data structure of a hash table to quickly locate the corresponding value through the hash code of the key. The key-value pairs in HashMap have no fixed order, so it is not suitable for scenarios that need to be traversed in a certain order. HashMap supports null as key and value.

The advantage of HashMap is that the time complexity of insertion, deletion and query is O(1), which is very efficient. The disadvantage of HashMap is that it does not support thread safety, so synchronization operations are required in a multi-threaded environment. In addition, when there are more and more elements in the hash table, the performance of the hash table will decrease.

TreeMap

TreeMap is a Map implementation based on red-black trees. It supports sorting according to the natural order of keys (such as lexicographic order for String) or a custom order. Key-value pairs in TreeMap are ordered.

The advantage of TreeMap is that it supports traversal in the order of keys, and the time complexity of insertion, deletion and query is O(logn), which is relatively efficient. In addition, TreeMap’s iterators are ordered. The disadvantage of TreeMap is that its space complexity is relatively high because it requires additional maintenance of the red-black tree structure.

LinkedHashMap

LinkedHashMap is a Map implementation with a predictable iteration order. It inherits the characteristics of HashMap and uses a doubly linked list to maintain the insertion order or access order. Key-value pairs in LinkedHashMap are ordered.

The advantage of LinkedHashMap is that it supports traversal in insertion order or access order. At the same time, the time complexity of insertion, deletion and query is O(1), which is relatively efficient. The disadvantage of LinkedHashMap is that its space complexity is relatively high because it requires an additional two-way linked list to be maintained.

ConcurrentHashMap

ConcurrentHashMap is a thread-safe Map implementation. It uses a segmented lock mechanism to ensure thread safety and has better concurrency performance than Hashtable. There is no fixed order for key-value pairs in ConcurrentHashMap.

The advantage of ConcurrentHashMap is that it supports thread safety, and the time complexity of insertion, deletion and query is O(1), which is relatively efficient. The disadvantage of ConcurrentHashMap is that its space complexity is relatively high because it requires additional maintenance of multiple Segments.

How to use Map?

Add key-value pairs

Use the put() method to add key-value pairs to the Map, for example:

java

Copy code

Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2);
Delete key-value pairs

Use the remove() method to delete key-value pairs in the Map, for example:

java

Copy code

map.remove("apple");
Update key-value pairs

Use the put() method to update the key-value pairs in the Map, for example:

java

Copy code

map.put("banana", 3);
Query key-value pairs

Use the get() method to query the key-value pairs in the Map, for example:

java

Copy code

int value = map.get("banana");

Efficiently operate key-value pairs

In practical applications, we need to perform a large number of operations on key-value pairs. How to operate Map efficiently is an issue we need to pay attention to. Here are some common operating tips.

Traverse Map

You can use foreach or iterator to traverse the Map. If you need to traverse in the order of keys, you can use TreeMap or LinkedHashMap.

java

Copy code

Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); // foreach for (Map.Entry<String, Integer> entry : map.entrySet()) { String key = entry.getKey(); int value = entry.getValue(); } // IteratorIterator<Map.Entry<String, Integer>> iterator = map.entrySet() .iterator(); while (iterator.hasNext()) { Map.Entry<String, Integer> entry = iterator.next(); String key = entry.getKey(); int value = entry.getValue(); } / / Traverse Map<String, Integer> in the order of keys map2 = new TreeMap<>(); map2.put("apple", 1); map2.put("banana", 2); for (Map.Entry<String , Integer> entry : map2.entrySet()) { String key = entry.getKey(); int value = entry.getValue(); }
Determine whether the Map contains a certain key or value

Use the containsKey() method to determine whether the Map contains a certain key, and the containsValue() method to determine whether the Map contains a certain value.

java

Copy code

Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); boolean containsKey = map.containsKey("apple"); boolean containsValue = map.containsValue(2);
Get the size of Map

Use the size() method to get the size of the Map.

java

Copy code

Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); int size = map.size();
Avoid creating objects frequently

In frequent operations, creating objects is a time-consuming operation. In order to improve performance, we should try to avoid creating objects frequently. For example, when traversing key-value pairs in a Map, you can define the key or value as a member variable of the class and reuse it during the traversal process, for example:

java

Copy code

class MyObject { String key; int value; } Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); List<MyObject > list = new ArrayList<>(); for (Map.Entry<String, Integer> entry : map.entrySet()) { MyObject object = new MyObject(); object.key = entry.getKey(); object.value = entry.getValue(); list.add(object); }
Try to use iterators to operate Map

When traversing a Map, try to use iterator operations. The advantage of using iterators is that elements can be deleted or modified during the traversal process without throwing ConcurrentModificationException. For example:

java

Copy code

Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Integer> entry = iterator.next(); String key = entry.getKey(); int value = entry.getValue (); if (value == 2) { iterator.remove(); // Remove the element with value 2} if (key.equals("apple")) { entry.setValue(3); // Change value to The element of 1 is updated to 3 } }

Test cases

Below are test cases for several common methods. The sample code is as follows.

Test put method
java

Copy code

// Test the put method @Test public void Put() { Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); assertEquals(3, map.size()); map.put("apple", 4); assertEquals(3, map.size()); }

The test case is executed as follows:

Test get method
java

Copy code

//Test the get method @Test public void testGet() { Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); System.out.println("map=" + map); System.out.println(map.get("banana").intValue()); assertEquals(2, map .get("banana").intValue()); }

The test case is executed as follows:

Test remove method
java

Copy code

// Test the remove method @Test public void testRemove() { Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); System.out.println("map=" + map before removal); map.remove("banana"); System.out.println("map=" after removal + map); assertEquals(2, map.size()); assertNull(map.get("banana")); }

The test case is executed as follows:

Test containsKey method
java

Copy code

// Test the containsKey method @Test public void testContainsKey() { Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); System.out.println("map=" + map); System.out.println("map.containsKey("orange") = " + map.containsKey(" orange")); assertTrue(map.containsKey("orange")); }

The test case is executed as follows:

The above is an introduction to test cases for some common methods of Map in Java. I hope it can help everyone better understand and master Map, a commonly used data structure.

Full text summary

Finally, let’s summarize that Map is one of the commonly used data structures in Java, used to store key-value pairs. There are many implementation classes of Map, such as HashMap, TreeMap, LinkedHashMap, etc. You need to pay attention to the following points when using Map:

  • The keys in the Map must be unique and the values can be repeated.

  • HashMap is the most commonly used Map implementation class, and the time complexity of its search, insertion, and deletion operations is O(1).

  • TreeMap is an ordered Map, which is implemented internally using a red-black tree, which ensures that the elements are sorted according to the natural order of the keys.

  • LinkedHashMap can ensure that the order of elements is the same as the order of addition, and can be used to implement application scenarios such as caching.

In summary, Map is one of the most commonly used data structures in Java. By choosing different implementation classes and operation methods, key-value pairs can be operated efficiently.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Algorithm skill tree Home page Overview 52251 people are learning the system