[Java] 遍歷HashMap和HashMap轉換成List的兩種方式


遍歷HashMap和HashMap轉換成List

 

/**
* convert the map to the list(1)
*/
public static void main(String[] args) {
   Map<String, String> maps = new HashMap<String, String>();
   maps.put("a", "aa");
   maps.put("b", "bb");
   maps.put("c", "cc");
   maps.put("d", "dd");
   maps.put("e", "ee");
   maps.put("f", "ff");
  
   List<String> strList = new ArrayList<String>();
  
   for (String str : maps.values()) {
    strList.add(str);
   }
  
   for (int i = 0; i < strList.size(); i++) {
   
    System.out.println(strList.get(i));
   }
}

 

/**
* convert the map to the list(2)
*/
public static void main(String[] args) {
   Map<String, String> maps = new HashMap<String, String>();
   maps.put("a", "aa");
   maps.put("b", "bb");
   maps.put("c", "cc");
   maps.put("d", "dd");
   maps.put("e", "ee");
   maps.put("f", "ff");
  
   List<String> strList = new ArrayList<String>(maps.values());
  
   for (int i = 0; i < strList.size(); i++) {
   
    System.out.println(strList.get(i));
   }
}

 

控制台輸出結果:

dd
aa
cc
ff
bb
ee

(HashMap無序排列)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM