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

Java 8Object Oriented ProgrammingProgramming

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

Map<String, String>map = new LinkedHashMap<String, String>();
map.put("1", "Katie");
map.put("2", "Peter");
map.put("3", "Amy");
map.put("4", "Kane");
map.put("5", "Colin");
map.put("6", "Andre");
map.put("7", "Pollard");
map.put("8", "David");
map.put("9", "Jofra");
map.put("10", "Akila");

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

List<String>list = new ArrayList<String>();
list.addAll(map.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>map = new LinkedHashMap<String, String>();
      map.put("1", "Katie");
      map.put("2", "Peter");
      map.put("3", "Amy");
      map.put("4", "Kane");
      map.put("5", "Colin");
      map.put("6", "Andre");
      map.put("7", "Pollard");
      map.put("8", "David");
      map.put("9", "Jofra");
      map.put("10", "Akila");
      List<String>list = new ArrayList<String>();
      list.addAll(map.keySet());
      System.out.println("Keys...");
      for (String str: list) {
         System.out.println(str);
      }
   }
}

Output

Keys...
1
2
3
4
5
6
7
8
9
10
raja
Published on 24-Apr-2019 14:56:01
Advertisements