Find keys from both the Linked HashMap and store it in a list alternatively

you have two LinkedHashMaps

Map m1 = new LinkedHashMap();
m1.put("1","One");
m1.put("3","Three");
Map m2 = new LinkedHashMap();
m2.put("2","Two");
m2.put("4","Four");

Find keys from both the Linked HashMap and store it in a list alternatively.

The list should contain 1,2,3,4.

Answers


This is solution:

        List list = new ArrayList();
        list.addAll(m1.keySet());
        list.addAll(m2.keySet());
        Collections.sort(list);

Really sounds like homework, so I won't give you the exact code. I think the answers so far are wrong, as they don't interleave. Try this:

Get an Iterator iterator1 for the first map. Get an Iterator iterator2 for the second map.

Use a while loop and ask for the next element in iterator1 and iterator2. The rest is for you to figure out.


You can create a list and add both keySets from your maps, like so:

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class Main {

    public static void main(String[] args) {
        Map m1 = new LinkedHashMap();
        m1.put("1","One");
        m1.put("3","Three");
        Map m2 = new LinkedHashMap();
        m2.put("2","Two");
        m2.put("4","Four");
        List<String> list = new ArrayList<String>();
        list.addAll(m1.keySet());
        list.addAll(m2.keySet());
        for(String s : list) {
            System.out.println(s);
        }
    }

}

Need Your Help

Castle Windsor Lifestyle configuration

inversion-of-control castle-windsor

I've spent some time looking around, and there doesn't seem to be an obvious solution to this scenario.

Passing data (list) from view to controller with TextBox

javascript asp.net asp.net-mvc asp.net-mvc-4 razor

I'm using ASP MVC4 with razor and I'm stuck to return some infos from my view to my controller in a list with the below elements...