Home Java javaTutorial Analysis of nine major problems with Map in Java

Analysis of nine major problems with Map in Java

Jan 19, 2017 am 10:38 AM
java map

Generally speaking, Map is a data structure composed of key-value pairs, and each key in the collection is unique. Let's use K and V to represent keys and values ​​to explain the nine major issues about Map in Java.
0. Convert Map to List type
In Java, the Map interface provides three collection acquisition methods: Key set, value set, and key-value set. They can all be converted to List type through the constructor or addAll() method. The following code explains how to construct an ArrayList from a Map:

// key list
List keyList = new ArrayList(map.keySet());
// value list
List valueList = new ArrayList(map.valueSet());
// key-value list
List entryList = new ArrayList(map.entrySet());
Copy after login

1. Traverse the Map through Entry
This way of existing as key-value pairs in java is called a Map. Entry. Map.entrySet() returns a key-value set, which is a very efficient traversal method.

for(Entry entry: map.entrySet()) {
// get key
K key = entry.getKey();
// get value
V value = entry.getValue();
}
Copy after login

Iterator We also often use it, especially before JDK1.5

Iterator itr = map.entrySet().iterator();
while(itr.hasNext()) {
Entry entry = itr.next();
// get key
K key = entry.getKey();
// get value
V value = entry.getValue();
}
Copy after login

2. Sort Map by Key
Sort requires frequent operations on the ke of the Map. One way is to implement it through a comparator:

List list = new ArrayList(map.entrySet());
Collections.sort(list, new Comparator() {
@Override
public int compare(Entry e1, Entry e2) {
return e1.getKey().compareTo(e2.getKey());
}
});
Copy after login

The other way is through SortedMap, but it must be implemented Comparable interface.

SortedMap sortedMap = new TreeMap(new Comparator() {
@Override
public int compare(K k1, K k2) {
return k1.compareTo(k2);
}
});
sortedMap.putAll(map);
Copy after login

3. Sort the Map by value
This is somewhat similar to the previous point. The code is as follows:

List list = new ArrayList(map.entrySet());
Collections.sort(list, new Comparator() {
@Override
public int compare(Entry e1, Entry e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
Copy after login

4. Initialization A static constant Map

When you want to create a global static Map, we have the following two methods, and they are thread-safe.
In Test1, although we declared that map is static, we can still change its value during initialization, just like Test1.map.put(3,"three");
In Test2 , we pass an inner class and set it to be unmodifiable, then when we run Test2.map.put(3, "three"), it will throw a

UnsupportedOperationException 异常来禁止你修改。
 public class Test1 {
private static final Map map;
static {
map = new HashMap();
map.put(1, "one");
map.put(2, "two");
}
}
public class Test2 {
private static final Map map;
static {
Map aMap = new HashMap();
aMap.put(1, "one");
aMap.put(2, "two");
map = Collections.unmodifiableMap(aMap);
}
}
Copy after login

5. Differences between HashMap, TreeMap, and Hashtable
In the Map interface, there are three implementations: HashMap, TreeMap, and Hashtable.
They are different. For details, please refer to the article "HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap".

6. Reverse query in Map
After we add a key-value pair to the Map, it means that the keys and values ​​in the Map have a one-to-one correspondence, and one key corresponds to one value. But sometimes we need reverse query, such as finding its key through a certain value. This data structure is called bidirectional map. Unfortunately, JDK does not support it.
Apache and Guava jointly provide this bidirectional map implementation. In the implementation, it stipulates that both keys and values ​​must have a 1:1 relationship.

7. Copying Map
Java provides many methods to copy a Map, but those methods may not always be synchronized. Simply put, when a Map changes, the copied one remains the same. The following is a more efficient implementation method:
Map copiedMap = Collections.synchronizedMap(map);
Of course there is another method, which is cloning. However, our Java originator Josh Bloch does not recommend this approach. He once said in an interview about the issue of Map cloning: Cloning methods are provided in many classes because people really need it. But cloning is very limiting, and in many cases causes unnecessary effects.
8. Create an empty Map
If this map is set to be unavailable, it can be achieved through the following
map = Collections.emptyMap();
On the contrary, when we use it, just You can directly
map = new HashMap();

The above is the entire content of this article. I hope it will be helpful to everyone's learning, and I also hope that everyone will support the PHP Chinese website.

For more related articles on the analysis of the nine major problems of Map in java, please pay attention to the PHP Chinese website!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Map performance optimization revealed: Make your data operations faster and more efficient Java Map performance optimization revealed: Make your data operations faster and more efficient Feb 20, 2024 am 08:31 AM

JavaMap is a commonly used data structure in the Java standard library, which stores data in the form of key-value pairs. The performance of Map is crucial to the running efficiency of the application. If the performance of Map is poor, it may cause the application to run slowly or even crash. 1. Choose the appropriate Map implementation Java provides a variety of Map implementations, including HashMap, TreeMap and LinkedHashMap. Each Map implementation has its own advantages and disadvantages. When choosing a Map implementation, you need to choose the appropriate implementation based on the specific needs of the application. HashMap: HashMap is the most commonly used Map implementation. It uses hash tables to store data and has faster insertion, deletion and search speeds.

Java Map Revealed: Tips and Strategies for Fast Data Access Java Map Revealed: Tips and Strategies for Fast Data Access Feb 19, 2024 pm 06:21 PM

JavaMap is a key-value pair-based data structure that allows developers to quickly store and retrieve data. The keys of a Map can be any object, and the values ​​can be any type of data. Each key in the Map can only be associated with at most one value. If multiple values ​​are set for the same key, only the last set value will be retained. There are two main implementations of Map: HashMap: uses a hash table to store key-value pairs. The performance of HashMap depends on how the hash table is implemented, and in most cases HashMap performs better than TreeMap. TreeMap: uses red-black trees to store key-value pairs. The performance of TreeMap is similar to HashMap, but in some cases, the performance of TreeMap can be

Demystifying Java Map: A simple and easy-to-understand guide to traversal Demystifying Java Map: A simple and easy-to-understand guide to traversal Feb 20, 2024 pm 12:00 PM

1. Overview Map is a member of the Java collection framework, which stores elements in the form of key-value pairs, allowing quick retrieval and modification of data. Due to its powerful functions and wide application, mastering Map traversal methods is an essential skill for Java programmers. 2. Traversal method Map provides a variety of traversal methods. Each method has its own advantages and disadvantages and can be selected according to specific needs. 3.keySet() traverses the keySet() method to return a collection of all keys in the Map. You can traverse the keys through an iterator or an enhanced for loop to obtain the corresponding value. //Use keySet() to traverse MapMapmap=newHashMap();map.

Advanced skills of Java Map: Master cold knowledge you may not know and improve your programming skills Advanced skills of Java Map: Master cold knowledge you may not know and improve your programming skills Feb 19, 2024 pm 12:33 PM

Map interface overview The Map interface is a data structure used to store key-value pairs in the Java collection framework. It allows you to use keys to find and retrieve associated values. The Map interface provides many useful methods, including put(), get(), remove(), containsKey(), containsValue(), size(), isEmpty(), etc. Implementation of Map The most commonly used Map implementations in Java are HashMap and TreeMap. HashMap is a hash table-based Map implementation that quickly finds and retrieves values ​​by calculating the hash value of the key. TreeMap is a Map implementation based on red-black trees, which sorts keys in ascending or descending order.

Master the essence of Java Map, a necessary skill for advanced learners Master the essence of Java Map, a necessary skill for advanced learners Feb 19, 2024 pm 06:00 PM

JavaMap is a data structure that allows you to store and retrieve values ​​using keys. Keys in a Map are unique, which means you cannot store two values ​​with the same key. The values ​​in the Map can be any object, including other Maps. Map has many uses in Java. For example, you can use a Map to store user IDs and passwords, product IDs and prices, or file names and file contents. Maps are also great for storing configuration settings within an application. There are three built-in Map implementations in Java: HashMap, TreeMap and LinkedHashMap. HashMap is a Map implementation based on hash tables, and it is the most widely used Map implementation. TreeMap is based on

Java Map in enterprise applications: Explore its powerful role in real projects Java Map in enterprise applications: Explore its powerful role in real projects Feb 19, 2024 pm 01:27 PM

JavaMap is a data structure that allows you to store data using key-value pairs. Keys are unique while values ​​can be any type of data. Map can be implemented in many ways, including HashMap, TreeMap and ConcurrentHashMap. In enterprise-level applications, Maps can be used for a variety of purposes. For example, you can use a Map to: Store user data such as names, email addresses, and passwords. Stores product data such as name, price, and description. Stores order data such as customer name, address and items purchased. Stores cached data, such as recently visited web pages or database query results. Maps are great for storing complex data structures. For example, you can use Ma

Extension and customization of Java Map: Create your own data structure to meet your customization needs Extension and customization of Java Map: Create your own data structure to meet your customization needs Feb 19, 2024 pm 09:50 PM

JavaMap is a very useful data structure that can be used in various application scenarios. But sometimes, we may need to extend or customize the Map to meet specific needs, such as adding new functionality, changing the traversal order, or creating a custom serializer. This article will introduce how to extend and customize JavaMap to help you create your own data structure to meet your customization needs. 1. Extend JavaMap The simplest way to extend JavaMap is to create a new class that inherits from the java.util.Map interface. This new class can add new methods or properties, and can also override methods in the Map interface. For example, we can create a new Map class and add a new method to calculate the sum of key-value pairs: publ

Explore the charm of Java Map and solve the problems of data processing Explore the charm of Java Map and solve the problems of data processing Feb 19, 2024 pm 07:03 PM

Explanation of Map Map is a data structure that allows you to store key-value pairs. The keys are unique and the values ​​can be any type of object. The Map interface provides methods for storing and retrieving key-value pairs, and allows you to traverse the key-value pairs in the Map. Types of Map There are several different implementations of Map in Java, the most common ones are HashMap, TreeMap and LinkedHashMap. HashMap: A Map implementation based on a hash table, which has the characteristics of fast search, insertion and deletion, but it is not ordered, which means that the order of key-value pairs in the Map is arbitrarily determined. TreeMap: A Map implementation based on red-black trees, with the characteristics of fast search, insertion and deletion, and it has

See all articles