» » Map to list in java example

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6.  
  7. public class MapKeyToList {
  8.  
  9.  Map<Integer, String> map;
  10.  
  11.  public MapKeyToList(Map<Integer, String> map) {
  12.  this.map = map;
  13. }
  14.  
  15.  public List<Integer> convertKeysToList() {
  16.    return new ArrayList(map.keySet());   
  17. }   

  18. public static void main(String[] args) {
  19.  
  20.  Map<Integer, String> map = new HashMap<>();
  21.     map.put(1, "one");
  22.     map.put(2, "two");
  23.     map.put(3, "three");
  24.     map.put(4, "Four");
  25.     map.put(5, "Five");
  26.     map.put(6, "Six");
  27.     map.put(7, "Seven");
  28.     map.put(9, "Nine");
  29.     map.put(10, "Ten");
  30.  
  31.     MapKeyToList conv = new MapKeyToList(map);
  32.     List<Integer> keysList = conv.convertKeysToList();
  33.  
  34.      System.out.println("Keys:");
  35.  
  36.      for (Integer key : keysList) {
  37.         System.out.println(key);
  38.    }
  39.  
  40.  }
  41. }
  42. OutPut:
  43. Keys:
  44. 1
  45. 2
  46. 3
  47. 4
  48. 5
  49. 6
  50. 7
  51. 8
  52. 9
  53. 10

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu