-2

How to create a new Map using data in an existing Map?

for example, I have existing data on a previously calculated map. which contains

Map<String, Object> map1 = new HashMap<>();
List<String> names = new ArrayList<>();
list.add("name lastName 1");
list.add("name lastName 2");
map1.put("Name",list);

List<Integer> ages = new ArrayList<>();
list.add("30");
list.add("40");
map1.put("Ages",ages);

I need to create a new Map which dynamically.

Map<String, Object> newMap = new HashMap<>();
newMap.put("FullName","name lastName 1");
newMap.put("Ages",30);

do a special code after that get new values for (name lastName 2, age2) etc...

what I mean is that my entries on the first map could be changed during its calculation.

Many thanks.

  • Does this answer your question? [How to convert a Map to List in Java?](https://stackoverflow.com/questions/1026723/how-to-convert-a-map-to-list-in-java) – Felix Apr 02 '20 at 17:38

2 Answers2

0

You can do this way

for (int i = 0; i < ((List<String>) map1.get("Name")).size(); i++) {
    Map<String, Object> newMap = new HashMap<>();
    newMap.put("Name", ((List<String>) map1.get("Name")).get(i));
    newMap.put("Last", ((List<String>) map1.get("LastName")).get(i));

    System.out.println(newMap);
}


// {Last=LastName1, Name=name1}
// {Last=LastName2, Name=name2}
azro
  • 53,056
  • 7
  • 34
  • 70
0

You should not use Map<String, Object> for map1, use Map<String, List<String>>. Then you can iterate through it like this:

for (int i = 0; i < map1.get("Name").size(); i++) {
    Map<String, String> newMap = new HashMap<>();
    newMap.put("Name", map1.get("Name").get(i);
    newMap.put("Last", map1.get("LastName").get(i);
    .......
}
Alex Sveshnikov
  • 4,214
  • 1
  • 10
  • 26