JavaRush /Java Blog /Random EN /Top 9 questions about Map in Java
Treefeed
Level 21

Top 9 questions about Map in Java

Published in the Random EN group
Recall that a Map is structured data consisting of a set of key-value pairs, and each key can only be used once in a single Map. This topic covers 9 basic questions about using Map in Java and its implemented classes. For simplicity, I will use generalizations in the examples . Therefore, I will write simply Map, without specifying the Map specifier. But you can assume that both values ​​of K and V are comparable, which means K extends Comparable and V also extends Comparable .Top 9 Questions About Map in Java - 1

0. Converting a Map to a List

In Java, the Map interface offers three kinds of collections: a key set, a value set, and a key-value set. All of them can be turned into a List using the constructor or method addAll(). The following code snippet demonstrates how to make an ArrayList from a Map.
// list of keys
List keyList = new ArrayList(Map.keySet());
//list of values
List valueList = new ArrayList(Map.valueSet());
//list key-value
List entryList = new ArrayList(Map.entrySet());

1. Loop through all the values ​​in the Map

Walking through each key-value pair is the most basic, basic procedure for walking through a Map. In Java, each pair is stored in a Map field called Map.Entry . Map.entrySet()returns a set of key-values, so the most efficient way to iterate through all the values ​​of a Map would be:
for(Entry entry: Map.entrySet()) {
  //get the key
  K key = entry.getKey();
  //get value
  V value = entry.getValue();
}
We can also use Iterator, especially in versions younger than JDK 1.5
Iterator itr = Map.entrySet().iterator();
while(itr.hasNext()) {
  Entry entry = itr.next();
  //get the key
  K key = entry.getKey();
  //get value
  V value = entry.getValue();
}

2. Ordering Map by Keys

Organizing Maps by keys is another commonly used procedure. The first way is to add Map.Entry to the list, and sort using a comparator that sorts by values.
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: use SortedMap , which, in addition, also arranges its keys in order. But, all keys must embody Comparable or be accepted by the comparator. One of the implemented classes SortedMapis TreeMap . Its constructor accepts a comparator. The following code shows how to turn a normal one Mapinto an ordered one.
SortedMap sortedMap = new TreeMap(new Comparator() {

  @Override
  public int compare(K k1, K k2) {
    return k1.compareTo(k2);
  }

});
sortedMap.putAll(Map);

3. Order Map by Values

Adding a Map to the list and then sorting it works in this case, but this time you need to use Entry.getValue(). The code below is almost the same as before.
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());
  }

});
We can still use it SortedMapin this case, but only if the values ​​are unique. In this case, you can turn the key-value pair into a key-value. This solution has severe limitations and is not recommended by me.

4. Initializing a static/immutable Map

When you want a Map to remain immutable, a good way is to copy it to an immutable Map. This defensive programming technique will help you create a Map that is not only safe to use, but also thread-safe. To initialize a static/immutable Map, we can use an initializer static(see below). The problem with this code is that despite declaring a Map as static final, we can still work with it after initialization, for example Test.Map.put(3,"three");. So it's not real immutability. To create an immutable Map using a static initializer, we need a super anonymous class, which we will add to the immutable Map at the last initialization step. Please look at the second part of the code. When an UnsupportedOperationException will be thrown if you run Test.Map.put(3,"three");.
public class Test {

  private static final Map Map;
  static {
    Map = new HashMap();
    Map.put(1, "one");
    Map.put(2, "two");
  }
}
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);
  }
}
The Guava library also supports various ways to initialize static and immutable collections. To learn more about the benefits of Guava's immutable collections utility, see the Immutable Collections section in the Guava How-to .

5. Difference between HashMap, TreeMap, and Hashtable

There are three main implementations of the Map interface in Java: HashMap , TreeMap , and Hashtable . The main differences are as follows:
  • Order of passage . HashMap and HashTable do not guarantee the ordering of the Map; in particular, they do not guarantee that the order will remain the same over time. But TreeMapit will order all values ​​in the "natural order" of the keys or by a comparator.
  • Valid key-value pairs. HashMapallows you to have a null key and a null value. HashTabledoes not allow a null key or null value. If TreeMapnatural order is used or the comparator does not allow a null key, an exception will be thrown.
  • Synchronization . Only HashTablesynchronized, the rest are not. But, "if a thread-safe implementation is not needed, it is recommended to use " HashMapinstead HashTable.
More detailed comparison
.                       | HashMap | HashTable | TreeMap
-------------------------------------------------------

Упорядочивание          |нет      |нет        | да
null в ключ-meaning    | да-да   | нет-нет   | нет-да
синхронизировано        | нет     | да        | нет
производительность      | O(1)    | O(1)      | O(log n)
воплощение              | корзины | корзины   | красно-чёрное дерево
Read more about the HashMap vs. relationship. TreeMap vs. Hashtable vs. LinkedHashMap .

6. Map with reverse search/view

Sometimes, we need a set of key-key pairs, which means the values ​​are as unique as the keys (a one-to-one pattern). This consistency allows you to create an "inverted view/search" on the Map. That is, we can find a key by its value. This data structure is called a bidirectional Map , which unfortunately is not supported by the JDK. Both Apache Common Collections and Guava offer bidirectional Map implementations called BidiMap and BiMap, respectively. Both introduce a constraint that enforces a 1:1 mapping between keys and values.

7. Shallow copy of Map

Almost all, if not all, Maps in Java contain a copy constructor for another Map. But the copying procedure is not synchronized. Which means when one thread copies a Map, another thread can change its structure. To prevent sudden copy desynchronization, one of them should be used in such a case Collections.synchronizedMap().
Map copiedMap = Collections.synchronizedMap(Map);
Another interesting way to copy shallowly is to use the clone(). But it is NOT recommended even by the creator of the Java collections framework, Joshua Bloch. In the " Copy Constructor vs. Cloning " debate, he takes the position: Quote: "I often provide a public clone method in concrete classes because people expect them to be there. ... it's a shame that Cloning is broken, but it happened. ... Cloning is a weak point and I think people should be warned about its limitations." For this reason, I don't even show you how to use the method clone()to copy Map

8. Create an empty Map

If Mapimmutable, use:
Map = Collections.emptyMap();
Or, use any other embodiment. For example:
Map = new HashMap();
END
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION