Simple Java: Nine Frequently Asked Questions about Java Maps, simplemaps

Source: Internet
Author: User
Tags comparable

Simple Java: Nine Frequently Asked Questions about Java Maps, simplemaps

In general, Map is a data structure composed of key-value pairs. The key cannot be repeated in Map;

This article summarizes the nine most common problems (about Java Map and Its Implementation classes );

For the sake of simplicity, I will not use generics in code examples. Therefore, I will write only Map rather than Map <K, V>, the keys and values in Map can be compared, meaning that both K and V implement the Comparable interface;

1. Map to List

In Java, the Map interface provides three set views: key set, value set, and key-value set. They can all be converted to a List set, as shown in the following code:

// key listList keyList = new ArrayList(map.keySet());// value listList valueList = new ArrayList(map.valueSet());// key-value listList entryList = new ArrayList(map.entrySet());
2. iteratively Traverse key-value in Map

Iterative traversal of key-value pairs in Map is the most basic operation. In Java, the key-Value Pair information is stored in the Map. Entry class. By calling the Map. entrySet () method, the key-value pair set is returned. Therefore, the most effective way to traverse the key-value pairs in the Map is as follows:

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

Of course, you can also traverse through the iterator, as shown in the following code:

while(itr.hasNext()) {    Entry entry = itr.next();    // get key    K key = entry.getKey();    // get value    V value = entry.getValue();}
3. Elements in Map are sorted by Key.

Sorting the elements in Map by key is another frequently used operation. One way is to put the elements in the Map into the List set and sort the set by a comparator, as shown in the following code example:

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

Another method is to use SortedMap, which provides the function of sorting keys. The premise is that the Key in Map needs to implement the Comparable interface or pass in the comparator through the constructor;

TreeMap is an implementation class of SortedMap. Its constructor can receive a comparator. The following code shows how to convert a normal Map into a SortedMap:

SortedMap sortedMap = new TreeMap(new Comparator() {    @Override    public int compare(K k1, K k2) {    return k1.compareTo(k2);    }});sortedMap.putAll(map);
4. Elements in Map are sorted by Value

You can also refer to the previous section to put the Map elements into the List set and pass in the comparator for sorting. However, the object to be compared this time is Entry. getValue (). The following code is used:

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

For this problem, when values in the map are unique, we can still use sorted map for sorting. In this case, you can assign the key to the value, value is assigned to the key to implement this function. However, this solution is very limited and is not recommended;

5. Initialize an unchangeable Map

When you want to use Map to store some constants, it is a good habit to store them to an unchangeable Map. This Defensive Programming technology will help you create a map that can be safely used and thread-safe;

We can use a static code block to initialize a static immutable map, as shown in the following code:

public class Test {private static final Map map;    static {        map = new HashMap();        map.put(1, "one");        map.put(2, "two");    }}

However, the above Code is problematic. Even if the map is declared as static final, we can still operate the map, such as Test. map. put (3, "three"); therefore, this is not an immutable map;

To create an immutable map, we need an extra map object, which is passed into the Collections. unmodifiableMap method as an input parameter, and an immutable Map is obtained. The following code:

public class Test {private static final Map map;static {Map aMap = new HashMap();aMap.put(1, "one");aMap.put(2, "two");map = Collections.unmodifiableMap(aMap);}}

At this point, when we run Test. map. put (3, "three"), the UnsupportedOperationException will be thrown;

Google's Guava Library supports multiple ways to create immutable maps. For more information, see its official user manual;

6. Differences between HashMap and TreeMap and Hashtable

HashMap, TreeMap, and Hashtable are the three main implementation classes of the Map interface. The main differences between them are as follows:

  • Order or not. HashMap and HashTable do not guarantee the orderliness of elements. Over time, the order of elements may change. However, TreeMap is ordered and sorted by natural order or comparator;
  • Key-value limit. HashMap allows the key and value to be null (only one key can be null, because the key cannot be repeated ). HashTable does not allow the key or value to be null. If the TreeMap uses natural sequence or the comparator does not allow the key to be null, an exception is thrown when the null key is used. In addition, in TreeMap, value can be null;
  • Whether to synchronize. Only Hashtable is synchronous, and others are not. If thread security is out of consideration, HashTable is strongly recommended.

Another complete comparison is as follows:

For more information about the comparison between them, refer to the following link:

Http://www.programcreek.com/2013/03/hashmap-vs-treemap-vs-hashtable-vs-linkedhashmap/

7. reverse search for Map

Sometimes, we need to have unique keys and values. In this case, we can create a bidirectional lookup Map. That is to say, we can use unique values to find the unique key. Unfortunately, JDK does not support this data structure;

Apache Common Collections and Guava provide support for two-way Map search, called BidiMap and BiMap. They define the relationship between key and value as one-to-one.

8. Map shortest copy

Most Map implementation classes provide constructor methods for copying another Map. However, this replication operation is not synchronous, meaning that when a thread replicates a Map, another thread may modify its structure (add or delete such operations). To prevent unexpected non-synchronous operations, Collections should be used in advance. the synchronizedMap () method creates a synchronous Map, as follows:

Map copiedMap = Collections.synchronizedMap(map);

The clone () method is used for the shallow COPY method. However, it is not recommended by the set framework author Josh Bloch; he talked about "copy constructor VS clone Method" in an interview. He said:

I often provide a public clone method on concrete classes because people else CT it .... it's a shame that Cloneable is broken, but it happens .... cloneable is a weak spot, and I think people shocould be aware of its limitations.

9. Create an empty Map

To create an immutable Map, use the Collections tool class as follows:

map = Collections.emptyMap();

Otherwise, use new directly, as shown below:

map = new HashMap();

 

Http://www.programcreek.com/2013/09/top-9-questions-for-java-map/.

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.