On the nine problems of map in Java _java

Source: Internet
Author: User

Typically, a map is a data structure made up of key-value pairs, and each key in the collection is unique. Here are the K and V to represent the keys and values to illustrate the nine major problems of map in Java.
0. Convert map to List type
in Java, the map interface provides three kinds of collection access: Key Set,,value set, and Key-value set. They can all be converted to the list type by constructing a method or a AddAll () method. The following code shows how to construct 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 ());

1, through the entry traversal map
in Java, this is known as map.entry in the form of key-value pairs. Map.entryset () returns a Key-value collection, which is a very efficient way to traverse.

 For (Entry Entry:map.entrySet ()) {
//Get key
K key = Entry.getkey ();
Get value
V value = Entry.getvalue ();
}

Iterator we often use them, 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 ();
}

2. Sort the map by key
sorting requires frequent manipulation of the ke of a map by means of a comparator (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 ());
}
);

Another way is through SortedMap, but you have to implement the comparable interface.

SortedMap SortedMap = new TreeMap (new Comparator () {
@Override public
int compare (k K1, K K2) {return
k1.c Ompareto (K2);
}
);
Sortedmap.putall (map);

3. Sort the map by value
This is somewhat similar to the above, with the following code:

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 ());
}
);

4. Initialize a static constant map

When you want to create a global static map, we have the following two ways, and are thread-safe.
In Test1, though, we declare that the map is static, but we can still change its value when initializing, just like Test1.map.put (3, "three");
In Test2, we set it as not modifiable through an inner class, so when we run Test2.map.put (3, "three") it throws a

Unsupportedoperationexception exceptions to prevent you from modifying. 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);
}
}

5. The difference between HashMap, TreeMap, and Hashtable
in the map interface, there are three implementations: Hashmap,treemap,hashtable.
There are differences between them, please refer to the article "HashMap vs. TreeMap vs. Hashtable vs. Linkedhashmap" For more information.

6. Reverse Query in Map
when we add a key value pair to the map, it means that the key and the value in the map correspond to one by one, and a key is the corresponding value. But sometimes we need to reverse query, such as a value to find its key, this data structure is called bidirectional map, unfortunately, the JDK does not support it.
Apache and guava together provide this bidirectional map implementation, which stipulates that both the key and the value must be 1:1 relationships.

7. Copy of Map
Java provides many ways to replicate a map, but those methods do not always synchronize. Simply put, it's the change that happens to a map, and the one that's copied remains intact. Here's a more efficient way to achieve this:
Map Copiedmap = Collections.synchronizedmap (map);
Of course there is another way, that is cloning. But our Java originator, Josh Bloch, does not recommend this approach, he once said in an interview about map cloning: In many classes, cloning is provided, because people do need. But cloning is very limited, and in many cases has caused unnecessary impact. (original "Copy constructor versus cloning")
8. Create an empty map
If this map is not available, you can use the following implementation
map = Collections.emptymap ();
on the contrary, when we use it, we can directly
map = new HashMap ();

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.