Nine big questions about map in Java

Source: Internet
Author: User

Typically, a map is a data structure that consists of key-value pairs, and each key in the collection is unique. Here are the keys and values in K and V to illustrate the nine major problems with maps in Java.

0. Convert map to List type

The map interface in Java provides three ways to get a collection: Key set,,value set, and Key-value set. They can all be converted to a list type by means of a constructor or AddAll () method. The following code shows how to construct the ArrayList from the 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. Traverse Map via entry

The way in which this key-value pair exists in Java is called Map.entry. 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 use it often, 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 map's Ke, one way to do this is through the 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 the comparable interface must be implemented.

SortedMap SortedMap = new TreeMap (new Comparator () {

@Override
public int compare (k K1, K K2) {
Return K1.compareto (K2);
}

});
Sortedmap.putall (map);

3. Sort the map by value

This is somewhat similar to the previous one, 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 at initialization we can still change its value, like Test1.map.put (3, "three");
In Test2, we use an inner class to set it to non-modifiable, so when we run Test2.map.put (3, "three"), it throws a Unsupportedoperationexception exception to prevent you from modifying it.

public class Test1 {

Private static final map map;
static {
Map = new HashMap ();
Map.put (1, "one");
Map.put (2, "a");
}
}

public class Test2 {

Private static final map map;
static {
Map AMap = new HashMap ();
Amap.put (1, "one");
Amap.put (2, "a");
Map = Collections.unmodifiablemap (AMAP);
}
}

5. The difference between HashMap, TreeMap, and Hashtable

In the map interface, there are three implementations: Hashmap,treemap,hashtable.

They are different, please refer to "HashMap vs. TreeMap vs. Hashtable vs. Linkedhashmap" For detailed information.

6. Reverse Query in Map

After 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 a 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 in its implementation specifies that both the key and the value must be a 1:1 relationship.

7, copy of the map

Java provides many ways to replicate a map, but those methods do not always synchronize. Simply put, there is a change in the map, and the copied one remains intact. The following is a more efficient implementation method:

Map Copiedmap = Collections.synchronizedmap (map);

Of course there is another way, that is cloning. But our Java originator, Josh Bloch, did not recommend this approach, and he once said in an interview about the problem of map cloning: In many classes, cloning is provided because people really need it. But cloning is very limited, and in many cases it has an unnecessary impact. (original Copy constructor versus cloning)

8. Create an empty map

If this map is set to not be available, you can use the following implementation

Map = Collections.emptymap ();

On the contrary, when we use it, we can directly

Map = new HashMap ();

Nine big questions about map in Java

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.