1. 程式人生 > >5種遍歷集合

5種遍歷集合

stat each循環 oid comm 如何 set 循環輸出 ger ava

  1. //循環遍歷map的方法
  2. public class MapF {
  3. public static void main(String[] args) {
  4. Map<String, Integer> tempMap = new HashMap<String, Integer>();
  5. tempMap.put("a","12");
  6. tempMap.put("b","34");
  7. tempMap.put("c","56");
  8. // JDK1.4中
  9. // 遍歷方法一 hashmap entrySet() 遍歷
  10. Iterator it = tempMap.entrySet().iterator();
  11. while (it.hasNext()) {
  12. Map.Entry entry = (Map.Entry) it.next();
  13. Object key = entry.getKey();
  14. Object value = entry.getValue();
  15. System.out.println("key=" + key + " value=" + value);
  16. }
  17. System.out.println("");
  18. // JDK1.5中,應用新特性For-Each循環
  19. // 遍歷方法二
  20. for (Map.Entry<String, Integer> entry : tempMap.entrySet()) {
  21. String key = entry.getKey().toString();
  22. String value = entry.getValue().toString();
  23. System.out.println("key=" + key + " value=" + value);
  24. }
  25. System.out.println("");
  26. // 遍歷方法三 hashmap keySet() 遍歷
  27. for (Iterator i = tempMap.keySet().iterator(); i.hasNext();) {
  28. Object obj = i.next();
  29. System.out.println(obj);// 循環輸出key
  30. System.out.println("key=" + obj + " value=" + tempMap.get(obj));
  31. }
  32. for (Iterator i = tempMap.values().iterator(); i.hasNext();) {
  33. Object obj = i.next();
  34. System.out.println(obj);// 循環輸出value
  35. }
  36. // 遍歷方法四 treemap keySet()遍歷
  37. for (Object o : tempMap.keySet()) {
  38. System.out.println("key=" + o + " value=" + tempMap.get(o));
  39. }
  40. System.out.println("11111");
  41. // java如何遍歷Map <String, ArrayList> map = new HashMap <String,
  42. // ArrayList>();
  43. System.out.println("java 遍歷Map <String, ArrayList> map = new HashMap<String, ArrayList>();");
  44. Map<String, ArrayList> map = new HashMap<String, ArrayList>();
  45. Set<String> keys = map.keySet();
  46. Iterator<String> iterator = keys.iterator();
  47. while (iterator.hasNext()) {
  48. String key = iterator.next();
  49. ArrayList arrayList = map.get(key);
  50. for (Object o : arrayList) {
  51. System.out.println(o);
  52. }
  53. }
  54. Map<String, List> map = new HashMap<String, List>();
  55. for (Map.Entry entry : map.entrySet()) {
  56. String key = entry.getKey().toString();
  57. List<String> list= (List) entry.getValue();
  58. for (String value : list) {
  59. System.out.println(key + "====" + value);
  60. }
  61. }
  62. }
  63. }

5種遍歷集合