Converting an Array to a Map in Java
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
import java.util.HashMap;
import java.util.Map;
public class ArrayToMapConverter {
public static void main(String[] args) {
// Sample array
String[] array = {"one", "two", "three", "four", "five"};
// Convert array to map
Map<Integer, String> resultMap = convertArrayToMap(array);
// Print the resulting map
System.out.println("Array to Map: " + resultMap);
}
private static Map<Integer, String> convertArrayToMap(String[] array) {
Map<Integer, String> map = new HashMap<>();
// Iterate through the array
for (int i = 0; i < array.length; i++) {
// Map each element to its index
map.put(i, array[i]);
}
return map;
}
}
|
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!