Summary of several major Map problems in java

Source: Internet
Author: User
Tags constructor


Generally, Map is a data structure composed of key-value pairs, and each key in the set is unique. The following uses K and V to represent keys and values, and describes nine Map problems in java.

0. Convert Map to List type

In java, the Map interface provides three collection methods: Key set, value set, and key-value set .. Both of them can be converted to the List type through the constructor or addAll () method. The following code illustrates 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 ());

1. Traverse Map through Entry

In java, this form of key-value pairs is called Map. Entry. Map. entrySet () returns a key-value set, which is a very efficient traversal method.

For (Entry entry Entry: map. entrySet ()){

// Get key

K key = entry. getKey ();

// Get value

V value = entry. getValue ();

}

Iterator is also frequently used, 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 Map by Key

Sorting requires frequent operations on the ke of the Map. One way is to achieve this through the 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 method is to use 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 values by Map

This is somewhat similar to the previous one. 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 ());

}

});

4. Initialize a static constant Map.

When you want to create a global static Map, we have two methods, which are thread-safe.
In Test1, although we declare that map is static, we can still change its value during initialization, just like Test1.map. put (3, "three ");
In Test2, we set it to unchangeable through an internal class, so when we run Test2.map. put (3, "three"), it will throw an UnsupportedOperationException to prohibit modification.

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. Differences between HashMap, TreeMap, and Hashtable

There are three implementations in the Map interface: HashMap, TreeMap, and Hashtable.

They are different from each other. For details, see HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap.

6. Reverse query in Map

After adding a key-value pair to Map, it means that the key-value pairs in Map correspond one to one, and one key corresponds to one value. However, sometimes we need reverse query, for example, to find its key through a value. This data structure is called bidirectional map. Unfortunately, JDK does not support it.

Apache and Guava jointly provide this bidirectional map implementation, which specifies that keys and values must be in a relationship.

7. Map replication

Java provides many methods for copying a Map, but those methods may not always be synchronized. Simply put, it is a Map change, and the copied one remains unchanged. The following is an efficient implementation method:

Map copiedMap = Collections. synchronizedMap (map );

Of course, there is another method, namely cloning. But Josh Bloch, the originator of java, does not recommend this method. He once said in an interview about Map cloning: the cloning method is provided in many classes, because people do. However, cloning is very limited, and in many cases it has caused unnecessary impact. (Original Copy constructor versus cloning)

8. Create an empty Map

If this map is set to unavailable, you can use the following implementation:

Map = Collections. emptyMap ();

Instead, we can directly

Map = new HashMap ();

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.