[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