Java Collection How to - Find keys from both the Linked HashMap and store it in a list alternatively








Question

We would like to know how to find keys from both the Linked HashMap and store it in a list alternatively.

Answer

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/*w w w . j  av a 2 s .co m*/
public class Main {

  public static void main(String[] args) {
    Map<String, String> m1 = new LinkedHashMap<String, String>();
    m1.put("1", "One");
    m1.put("3", "Three");

    Map<String, String> m2 = new LinkedHashMap<String, String>();
    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);
    }
  }

}

The code above generates the following result.