SoFunction
Updated on 2025-03-01

Java steps and code examples for exchanging key and value values ​​of maps

In Java, we all know that directly exchanging the key and value of a Map is not allowed, because the interface design of Map is based on key-value pairs, where the key is unique and immutable (in common implementations such as HashMap, although the reference to the key is immutable, the content of the key object itself can be varied if it is mutable, but doing so may lead to incorrect behavior or exceptions).

However, we can create a new map, take the value of the original map as the new key, and the key of the original map as the new value. But please note that if there are duplicate values ​​or null values ​​in the original map, this process may have problems, because the map's key must be unique and non-null.

Steps and code examples for exchanging the key and value values ​​of map

1.1 Detailed steps

(1)Define the original map: First, we need a primitive containing the key-value pairMap

(2)Check the uniqueness and non-empty nature of the value: Make sure the value is unique and non-null before exchanging. If the value is not unique or has a null value, we may need additional logic to handle these cases.

(3)Create a new map: Create a new oneMap, used to store the exchanged key-value pair.

(4)Iterate through the original map: traversal the originalMapEach entry, add value as the new key, and the key as the new value, to the newMapmiddle.

(5)Handle possible conflicts: If the value is not unique, we may need additional logic to handle this situation, such as usingListto store multiple keys with the same value.

1.2 Code Example

import .*;  
  
public class Main {  
    public static void main(String[] args) {  
        // Original Map        Map<String, Integer> originalMap = new HashMap<>();  
        ("A", 1);  
        ("B", 2);  
        ("C", 3);  
  
        // Check the uniqueness and non-empty nature of the value (for simplicity here, assuming that all values ​​are unique and non-null)  
        // Create a new map to store the exchanged key-value pairs        Map<Integer, String> swappedMap = new HashMap<>();  
  
        // Iterate through the original map and swap key and value        for (<String, Integer> entry : ()) {  
            // Assume that the value is non-null and we do not handle the value conflict here            ((), ());  
        }  
  
        // Output new map        for (<Integer, String> swappedEntry : ()) {  
            ("New Key: " + () + ", New Value: " + ());  
        }  
    }  
}

Note: This example assumes the originalMapThe values ​​are unique and non-null. If the value may not be unique or has a null value, we need to add additional logic to handle these cases.

Example of application scenarios for exchanging the key and value values ​​of maps

When it comes to exchangeMapWhen the key and value of , we need to consider some possible situations, such as the uniqueness of the value, whether the value is null, and whether multiple keys are allowed to correspond to the same new "key" (i.e., the original value). Here are a few examples of dealing with these situations:

2.1 Simple exchange (assuming value is unique and non-null)

import ;  
import ;  
  
public class SwapMapExample1 {  
    public static void main(String[] args) {  
        Map<String, Integer> originalMap = new HashMap<>();  
        ("A", 1);  
        ("B", 2);  
        ("C", 3);  
  
        Map<Integer, String> swappedMap = new HashMap<>();  
  
        for (<String, Integer> entry : ()) {  
            // Assume that the value is non-null and each value is unique            ((), ());  
        }  
  
        // Print the exchanged map        for (<Integer, String> swappedEntry : ()) {  
            ("New Key: " + () + ", New Value: " + ());  
        }  
    }  
}

2.2 Handle duplicate value

If the value may be repeated, then we need to decide how to deal with this situation. An easy way is to useListto store all keys with the same value.

import ;  
import ;  
import ;  
import ;  
  
public class SwapMapExample2 {  
    public static void main(String[] args) {  
        Map<String, Integer> originalMap = new HashMap<>();  
        ("A", 1);  
        ("B", 2);  
        ("C", 2); // Note that value 2 is repeated here  
        Map<Integer, List<String>> swappedMap = new HashMap<>();  
  
        for (<String, Integer> entry : ()) {  
            ((), new ArrayList<>()); // If the value does not exist, add a new ArrayList            (()).add(()); // Add key to the List of the corresponding value        }  
  
        // Print the exchanged map        for (<Integer, List<String>> swappedEntry : ()) {  
            ("New Key: " + () + ", New Values: " + ());  
        }  
    }  
}

2.3 Processing null value

If null values ​​may exist in the original map, we need to decide how to deal with them. An easy way is to ignore them or give them a special treatment.

import ;  
import ;  
  
public class SwapMapExample3 {  
    public static void main(String[] args) {  
        Map<String, Integer> originalMap = new HashMap<>();  
        ("A", 1);  
        ("B", null); // Note that there is a null value here        ("C", 3);  
  
        Map<Integer, String> swappedMap = new HashMap<>();  
  
        for (<String, Integer> entry : ()) {  
            if (() != null) { // Ignore null value                ((), ());  
            }  
        }  
  
        // Print the exchanged map        for (<Integer, String> swappedEntry : ()) {  
            ("New Key: " + () + ", New Value: " + ());  
        }  
    }  
}

These examples show how to handle different scenarios, including the uniqueness of the value, the null value, and the duplicate value. Depending on our specific needs, we can select or adjust the code in these examples.

3. How to map map to key-value pairs

In Java, when we mention "map maps to key-value pairs", it usually means that we have to iterate through each key-value pair of the map and do some operations on them, such as printing out, storing them to another data structure, or performing some transformation.

3.1 How to traverse aMapand get its key-value pair

Here is a simple example showing how to iterate over aMapAnd get its key-value pair:

import ;  
import ;  
  
public class MapExample {  
    public static void main(String[] args) {  
        // Create a HashMap        Map<String, Integer> map = new HashMap<>();  
        ("A", 1);  
        ("B", 2);  
        ("C", 3);  
  
        // Iterate through each key-value pair of the Map        for (<String, Integer> entry : ()) {  
            // Get keys and values            String key = ();  
            Integer value = ();  
  
            // Output keys and values            ("Key: " + key + ", Value: " + value);  
  
            // Here we can do whatever we need to do with keys and values            // For example, store it in another data structure, or perform conversion, etc.        }  
    }  
}

In the above code, we useentrySet()Method to get all key-value pairs in the Map. Then, we loop through this collection using for-each. In each iteration we can passgetKey()andgetValue()Methods obtain keys and values ​​respectively.

3.2 Combining keys and values ​​into a new object

If we want to map (convert) the key-value pairs of Map to another form, such as combining keys and values ​​into a new object, we can do this:

import ;  
import ;  
import ;  
import ;  
  
class KeyValuePair {  
    private String key;  
    private Integer value;  
  
    // Constructor, getter and setter methods (omitted here)  
    @Override  
    public String toString() {  
        return "Key: " + key + ", Value: " + value;  
    }  
}  
  
public class MapToMapExample {  
    public static void main(String[] args) {  
        // Create a HashMap        Map<String, Integer> map = new HashMap<>();  
        ("A", 1);  
        ("B", 2);  
        ("C", 3);  
  
        // Create a List to store the converted key-value pair object        List<KeyValuePair> keyValuePairs = new ArrayList<>();  
  
        // Iterate through each key-value pair of the Map and create a new KeyValuePair object        for (<String, Integer> entry : ()) {  
            KeyValuePair pair = new KeyValuePair();  
            (());  
            (());  
            (pair);  
        }  
  
        // Print the converted key-value pair list        for (KeyValuePair pair : keyValuePairs) {  
            (pair);  
        }  
    }  
}

In this example, we define a name calledKeyValuePairclass to store keys and values. We then iterate through the original map and create a new one for each key-value pairKeyValuePairObjects, and finally store these objects in a List.

3.3 Swap the keys and values ​​in the map

In Java, if we want to swap keys and values ​​in Map, we cannot directly operate on the same Map because the keys of the Map are unique and the value may not. However, we can create a new Map where the key of the original Map becomes the value of the new Map and the value of the original Map becomes the key of the new Map (if the value is unique and can be used as a key).

Here is a simple example showing how to swap keys and values ​​in a Map:

import ;  
import ;  
  
public class SwapMapKeyValue {  
    public static void main(String[] args) {  
        // Create an original HashMap        Map<String, Integer> originalMap = new HashMap<>();  
        ("A", 1);  
        ("B", 2);  
        ("C", 3);  
  
        // Create a new HashMap to store the exchanged key-value pairs        Map<Integer, String> swappedMap = new HashMap<>();  
  
        // Iterate through the original map and swap keys and values        for (<String, Integer> entry : ()) {  
            // Note: Here it is assumed that the value of the original map can be used as the key of the new map and there is no duplication            ((), ());  
        }  
  
        // Print the exchanged map        for (<Integer, String> entry : ()) {  
            ("Key: " + () + ", Value: " + ());  
        }  
    }  
}

In the example above, we created aoriginalMap, which contains string keys and integer values. Then we created a new oneHashMapswappedMap), its key is the value of the original Map, the value is the key of the original Map. We iterate through the original map and convert each key-value pair into a new key-value pair and then add it to the new map.

Note that this example assumes that the value in the original map can be used as the key to the new map and there are no duplicate values. If there are duplicate values ​​in the original map, then these values ​​will only have one corresponding key in the new map, because the keys of the map must be unique. Furthermore, if the values ​​of the original Map are not suitable key types (e.g., they are not hashed or they arenull), then this example will not work.

What is the difference between List

MapandListIt is two core interfaces in the Java Collections Framework. The main differences between them are reflected in the following aspects:

(1)Data structure:

  • Listis an ordered set (also known as a sequence) that contains elements that can be repeated. Each element in List has its corresponding index, through which you can access the elements. CommonListRealize thereArrayListLinkedListwait.

  • Mapis a collection of key-value pairs, where each key is unique and mapped to a value. Map does not guarantee the order of key-value pairs (exceptLinkedHashMapandTreeMap), and the values ​​can be repeated. CommonMapRealize thereHashMapTreeMapLinkedHashMapwait.

(2)Element access:

  • existListIn, you can access elements through index (an integer). For example,(0)The first element in the list will be returned.

  • existMapIn  , you cannot access elements through indexes, but access the corresponding value through keys. For example,("key")Returns the value associated with the key "key".

(3)Repeat elements:

  • ListAllow elements to be repeated, that is, the same element can appear multiple times in the list.

  • MapThe key of   is unique and repetition is not allowed, but the value can be repeated.

(4)method:

  • ListProvides a series of index-related methods, such asadd(int index, E element)remove(int index)get(int index)wait.

  • MapProvides a series of methods related to keys and values, such asput(K key, V value)get(Object key)remove(Object key)wait.

(5)Iteration:

  • You can useforLoop or iterator to traverseListelements in  .

  • ForMap, you can useentrySet()keySet()orvalues()Method to get a collection of key-value pairs, keys or values ​​and use iterators or enhancedforLoop (for-each loop) to traverse them.

(6)use:

  • ListUsually used to store ordered data sets, such as user lists, order lists, etc.

  • MapIt is usually used to store key-value pair data with unique keys, such as user information (user ID is used as key, user object is used as value), configuration parameters, etc.

In summary,MapandListThere are obvious differences in data structures, element access, element repetition, methods, iteration and use. The choice of which collection type to use depends on your specific needs and the characteristics of your data structure.

What are the application scenarios of Map in

In Java,MapInterface and implementation classes (such asHashMapTreeMapLinkedHashMapetc.) are very commonly used and powerful data structures, and they are widely used in various scenarios. Here are some common onesMapApplication scenarios in Java:

(1)Caching system:

  • Caches recently used or most commonly used data to improve program performance and responsiveness.

  • For example, session cache in web applications, cache database query results, etc.

(2)Configuration Management:

  • Read configuration files (e.g.propertiesFile orXMLfile) and store configuration items as key-value pairs inMapmiddle.

  • Allows the program to dynamically access and modify these configuration items at runtime.

(3)Database result map:

  • When processing database query results, map each row in the result set to oneMapObject, where the column name is the key and the column value is the value.

  • This can simplify data processing logic, especially when the structure of the result set changes frequently.

(4)URL parameter resolution:

  • Resolve query parameters in the URL (e.g.?key1=value1&key2=value2) and store them inMapmiddle.

  • This is very useful when handling web requests, making it easy to access and modify URL parameters.

(5)Routing and mapping:

  • In a web framework or routing system, useMapto map the URL path to the corresponding handler or controller.

  • It can also be used to map other types of identifiers (such as command ID, message type, etc.) to the corresponding processing logic.

(6)Mapping and transformation of collections:

  • Put a collection (such asListorSet) is mapped to elements in another collection or data structure.

  • For example, map an integer list to the corresponding string list (by()method).

(7)Statistics and counts:

  • useMapTo track and record the occurrence of various events or data points.

  • For example, count the number of visits to different pages in a website, analyze user behavior, etc.

(8)Dependency injection:

  • In some frameworks (such as Spring), useMapto manage and inject dependencies.

  • By mapping bean names to bean instancesMap, these beans can be easily accessed and used.

(9)Graphics and visualizations:

  • In graphics processing or visualization applications, useMapTo store information about nodes and edges.

  • For example, in a graph library, the node ID can be mapped to a node's properties and a list of adjacent nodes.

(10)Internationalization (i18n) and localization (l10n):

  • Store string resources from different languages ​​or regions and use language codes or region codes as keys to retrieve these resources.

  • This enables the application to support multiple languages ​​and regional settings.

(11)Algorithms and data structures:

In some algorithms and data structure implementations,MapUsed as an auxiliary data structure to speed up search, sort or calculation operations.

These are justMapIn some common application scenarios in Java, it actually has far more uses than these. becauseMapIt provides flexible key-value pair storage and retrieval mechanisms, so it has a wide range of applications in all types of applications.

The above is the detailed content of the steps and code examples for exchanging the key and value values ​​of Java maps. For more information about exchanging the key and value values ​​of Java maps, please pay attention to my other related articles!