Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a requirement where a map contains values which were the keys of other maps. Like below example

Java
Map<String, String> keysMap = new HashMap<>();
one.put("Car","4 Wheeler");
one.put("Bike","2 Wheeler");

Map<String, String> m1 =new HashMap<>();
m1.put("4 Wheeler","KIA");
m1.put("2 Wheeler","Bajaj");

Map<String, String> m2 = new HashMap<>();
m2.put("4 Wheeler","Hyundai");
m2.put("2 Wheeler","KTM");

List<Map<String, String>> listOfMaps= new ArrayList<>();
listOfMaps.add(m1);
listOfMaps.add(m2); // there could be more

List<Map<String, String>> result= new ArrayList<>();
for(Map<String, String> eachMap: listOfMaps){
     Map<String, String> singleMap = new HashMap<>();
     //help me here
}

Now I want keys of first map(one) as key to each new map(singleMap) for the values of second map(two) and third map(three) and so on

Required output should be like
Java
[
    { Car: "KIA", Bike: "Bajaj" },
    { Car: "Hyundai", Bike: "KTM" },
    //more
]


What I have tried:

I'm new to java and want to get a solution to thr above problem. I have tried getting all the values from keysMap and store it in a list and tried to iterate over the list of maps. But it seems very difficult to understand
Posted
Updated 3-Nov-21 23:48pm
v2
Comments
Richard MacCutchan 4-Nov-21 5:02am    
You just need a couple of loops. The outer loop iterates the main map and gets the keys (e.g. "Car") and their corresponding values (e.g. "4 Wheeler"). Then in the inner loop using the value from above as the key, you extract the corresponding values from each of the other maps, and print the results.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900