VOOZH about

URL: https://www.geeksforgeeks.org/java/converting-integer-string-hashmap-to-string-array-integer-hashmap-in-java/

⇱ Converting Integer-String HashMap to String-Array-Integer HashMap in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Converting Integer-String HashMap to String-Array-Integer HashMap in Java

Last Updated : 29 Dec, 2023

Efficient Conversion of a HashMap<Integer, String> into another HashMap<String, Integer[]> involves organizing integer keys based on their corresponding string values. Here's a concise and efficient Java method to accomplish this transformation, focusing on clear and straightforward implementation.

Step-by-Step Implementation of Conversion

The method follows a step-by-step procedure using HashMaps and Lists.

  • First, it gathers integer keys together by looking at their matching string values in a temporary HashMap.
  • Then, it turns these grouped keys into arrays, creating a fresh HashMap where strings are linked to arrays of integers.

Output
<aa,[7]>
<a,[1,3]>
<fg,[5]>
<b,[2,9]>
<k,[4]>
<vc,[10]>




Explanation of the above code:

  • This program uses the HashMap where numbers are linked to words and rearranges it.
  • It groups numbers based on the words they're linked to, creating arrays for each word with their corresponding numbers.
  • For example, the key "a" in the final map has the value [1, 3]. This means that in the input map, the String value "a" was associated with both the Integer keys 1 and 3.

Conclusion

This method provides an efficient way to convert a HashMap with integer keys and string values to a HashMap with string keys and integer arrays. It leverages temporary HashMaps and Lists for intermediate storage while prioritizing clear and straightforward implementation. The code effectively utilizes Java's built-in data structures and iterators, making it concise and easy to understand.

Comment