In Java, converting an array to a map can be a useful operation when you need to associate values with specific keys. This process involves iterating through the array and mapping each element to a corresponding key in the map. Let’s explore a simple example with working code:
importjava.util.HashMap;importjava.util.Map;publicclassArrayToMapConverter{publicstaticvoidmain(String[]args){// Sample arrayString[]array={"one","two","three","four","five"};// Convert array to mapMap<Integer,String>resultMap=convertArrayToMap(array);// Print the resulting mapSystem.out.println("Array to Map: "+resultMap);}privatestaticMap<Integer,String>convertArrayToMap(String[]array){Map<Integer,String>map=newHashMap<>();// Iterate through the arrayfor(inti=0;i<array.length;i++){// Map each element to its indexmap.put(i,array[i]);}returnmap;}}
Explanation:
We start by importing the necessary Java classes for handling maps (HashMap and Map).
In the ArrayToMapConverter class, we define a main method where we create a sample string array.
We then call the convertArrayToMap method to convert the array to a map and store the result in resultMap.
The convertArrayToMap method takes a string array as a parameter and initializes an empty HashMap.
We iterate through the array using a simple for loop, mapping each element to its corresponding index in the map.
Finally, the resulting map is returned.
This straightforward example demonstrates how to convert an array to a map in Java, providing a clear foundation for more complex scenarios.
Sharing is caring!