JavaMap summary

Features

  • key
  • value
  • Key-value pair (entry)
  1. A two-column collection needs to store a pair of data at a time, namely the key and the value.
  2. Keys cannot be repeated, values can be repeated
  3. Keys and values have a one-to-one correspondence, and each key can only find its corresponding value.
  4. Key + value form a “key-value pair object”

Common methods

v put(K key,V value) add element
V remove(Object key) Remove key-value pair elements based on key
void clear() removes all key-value pair elements
boolean containsKey(Object key) determines whether the collection contains the specified key
boolean containValue(Object value) determines whether the collection contains the specified value
boolean isEmpty() determines whether the collection is empty
int size() The length of the collection, that is, the number of key-value pairs in the collection
Object get() obtains the value of value through key

Map traversal method

1) Key to find value

Map<String,String> map=new HashMap<>();
        Set<String> strings = map.keySet();
        for (String string : strings) {<!-- -->
            map.get(string);
        }

2) Key-value pairs

Map<String,String> map=new HashMap<>();
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {<!-- -->
            String key=entry.getKey();
            String value=entry.getValue();
        }

Here Map.Entry entry Entry is the internal interface of Map

3) Lambda expression

anonymous inner class

Map<String,String> map=new HashMap<>();
        Set<Map.Entry<String, String>> entries = map.entrySet();
        map.forEach(new BiConsumer<String, String>() {<!-- -->
            @Override
            public void accept(String s, String s2) {<!-- -->
                System.out.println(s + s2);
            }
        });

lambda expression

Map<String,String> map=new HashMap<>();
        Set<Map.Entry<String, String>> entries = map.entrySet();
        map.forEach((s,s2)->{<!-- -->System.out.println(s + s2);});

Implementation class

  • HashMap: Unordered, non-repeating, non-indexed HashMap
  • LinkedHashMap: Ordered, no duplication, no index (see LinkedHashSet)
  • TreeMap: Sortable, no duplication, no index TreeMap

Different application scenarios

Different Map implementation classes are suitable for different application scenarios. Below, we will discuss some common scenarios of using Map in detail.

1. Data index

Maps can be used to build data indexes. When you need to quickly find a data item, using a HashMap or TreeMap can speed up the retrieval of the data because they provide O(1) or O(log n) retrieval time.

For example, you can use a HashMap to build an e-book chapter index, using the chapter title as the key and the chapter content as the value. In this way, you can quickly find the corresponding content based on the chapter title.

2. Data aggregation

Maps can be used for data aggregation. When you need to calculate the number of occurrences or the sum of a certain data item, you can use a Map to store the intermediate results.

For example, you can use a HashMap to count the number of occurrences of each word in a document. The keys can be words and the values can be the number of occurrences. Each time a word is encountered, you can check if it already exists in the Map and increment the count if it exists, otherwise add a new key-value pair.

3. Data sorting

If you need to iterate through data in a certain order, you can use a TreeMap. It maintains the order of keys based on their natural order or a custom comparator. This is useful when you need to view data in a specific order.

For example, you could use a TreeMap to store student grades, where the key could be the student’s name and the value could be the score. You can then iterate through student grades in alphabetical or fractional order to rank or find the top students.

4. Caching

Maps can also be used to build caches. You can use HashMap or LinkedHashMap to store already calculated results to avoid double calculations.

For example, if you have an expensive calculation task, you can store the calculation results in a HashMap for quick retrieval the next time you need the same result without having to recalculate it.

5. Maintain the order of key-value pairs

In some cases, you may need to maintain the order in which key-value pairs were inserted. LinkedHashMap is an implementation class suitable for this need, which can maintain the insertion order of key-value pairs.

For example, LinkedHashMap is a good choice when you need to display user information in the order in which they registered.

Differences from List

  1. How data is organized:

    • List: List is an ordered data structure that stores data in a linear manner. Each element has an index by which the element can be accessed. Elements in List can be repeated.

    • Map: Map is a data structure of key-value pairs, where each element has a unique key and the key is associated with the value. The keys in the Map are non-repeatable and each key is associated with a unique value. Maps usually store key-value pairs in no particular order.

  2. Data Access:

    • List: Access to List is based on index. You can get, add, update or delete elements through index. Because the elements in the List are ordered, you can get the element at a specific position based on the index.

    • Map: Access to Map is based on keys. You can use keys to find, add, update or delete key-value pairs. By making the key unique, you can quickly locate a specific value.

  3. Data Purpose:

    • List: List is usually used to store a set of elements, where the order of the elements is important. It is suitable for situations where the order of elements needs to be maintained or elements are allowed to be repeated, such as lists, arrays, queues, etc.

    • Map: Map is usually used to establish key-value relationships, where each key uniquely corresponds to a value. It is suitable for situations where key value lookup, association and mapping are required, such as dictionaries, hash tables, configuration files, etc.

  4. Common implementation classes:

    • List: Common List implementation classes include ArrayList, LinkedList, Vector, etc.

    • Map: Common Map implementation classes include HashMap, LinkedHashMap, TreeMap, etc.

  5. Performance Features:

    • List: List performs better when randomly accessing elements because it can be accessed directly based on the index. But when inserting or deleting elements, the performance may be poor, especially when inserting or deleting elements in the middle.

    • Map: Map performs well in finding, inserting and deleting elements because it is a key-based data structure. But it does not maintain the order of elements, so ordered traversal is not possible.

You need to store a set of elements in order, List is a more suitable choice. If you need to establish key-value relationships for efficient search and mapping, Map is a more suitable choice.