Home > Java > javaTutorial > body text

Analysis of nine major problems with Map in Java

高洛峰
Release: 2017-01-19 10:38:47
Original
1066 people have browsed it

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!


Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!