Java Program to find keys from both the Linked HashMap and store it in a list alternatively



Let us first create a LinkedHashMap with key-value pair −

Map<String, String>map1 = new LinkedHashMap<String, String>(); map1.put("1", "Jim"); map1.put("2", "David"); map1.put("3", "Tom"); map1.put("4", "Sam"); map1.put("5", "Steve");

Let us now create another LinkedHashMap with key-value pair −

Map<String, String>map2 = new LinkedHashMap<String, String>(); map2.put("6", "Katie"); map2.put("7", "John"); map2.put("8", "Kane"); map2.put("9", "Chris");

Now, create a new List and store the keys in it for both the above Map −

List<String>list = new ArrayList<String>(); list.addAll(map1.keySet()); list.addAll(map2.keySet());

Example

 Live Demo

import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class Demo {    public static void main(String[] args) {       Map<String, String>map1 = new LinkedHashMap<String, String>();       map1.put("1", "Jim");       map1.put("2", "David");       map1.put("3", "Tom");       map1.put("4", "Sam");       map1.put("5", "Steve");       Map<String, String>map2 = new LinkedHashMap<String, String>();       map2.put("6", "Katie");       map2.put("7", "John");       map2.put("8", "Kane");       map2.put("9", "Chris");       List<String>list = new ArrayList<String>();       list.addAll(map1.keySet());       list.addAll(map2.keySet());       System.out.println("Keys...");       for (String str: list) {          System.out.println(str);       }    } }

Output

Keys... 1 2 3 4 5 6 7 8 9
Updated on: 2019-07-30T22:30:25+05:30

132 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements