Aftab
Aftab

Reputation: 2963

How to Convert some custom Map object to LinkedHashMap?

Here is what I'm trying to do.

Map<String, List<Address>> mapObj = someService.getSomeAddress();

Using above call I'm getting mapObj of type Map<String, List<Address>>

And I want to send mapObj as a parameter in a another method (that I cannot change) as a LinkedHashMap<String, List<LinkedHashMap>> which does some further processing.

Is there any way that I can solve this problem without affecting data inside mapObj?

Upvotes: 0

Views: 2553

Answers (1)

anacron
anacron

Reputation: 6721

You will need to perform a couple of conversion steps.

  1. Convert all Address objects to LinkedHashMap objects.
  2. Put all Map entries into a LinkedHashMap object.

For 1st one, you can write a utility method some where that can do this conversion. For example,

public static List<LinkedHashMap> addresstoMap(List<Address> addresses)
{
    List<LinkedHashMap> list = new ArrayList<>();
    for(Address a: addresses){
        LinkedHashMap map = new LinkedHashMap();
        // Add address fields to map here
        list.add(map);
    }
    return list;
}

Then, for the 2nd step, you can do this:

LinkedHashMap<String, List<LinkedHashMap>> map = new LinkedHashMap<?,?>();

iterate through the entry sets of mapObj and put them into the above map object.

for (Map.Entry<String, List<Address>> e : m.entrySet()) {
    map.put(e.getKey(), addresstoMap(e.getValue()));
}

The final map object above will contain the correct representation in the LinkedHashMap<String, List<LinkedHashMap>> datatype.

Hope this helps!

Upvotes: 2

Related Questions