Map的遍历
1.通过map.entrySet遍历Key和Value
Map<Integer,Integer> map = new HashMap<>(); map.put(1, 10); map.put(2, 8); for(Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + " ---- " + entry.getValue() ); }
如果你遍历的Map是一个空的对象(null),for-each循环将会抛出java.lang.NullPointerException异常
2.通过map.keySet()来遍历key,通过map.values()来遍历Value,适用于只需要map中的Key或者Value的情况
Map<Integer,Integer> map = new HashMap<>(); map.put(1, 10); map.put(2, 8); for (Integer i : map.keySet()) { System.out.println(i); } for ( Integer i : map.values()) { System.out.println(i); }
3.通过Iterator遍历Map
//使用泛型Map<Integer,Integer> map = new HashMap<>(); map.put(1, 10); map.put(2, 8); Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Integer, Integer> temp = iterator.next(); System.out.println(temp.getKey() + " ----- " + temp.getValue()); } //不使用泛型Map<Integer,Integer> map = new HashMap<>(); map.put(1, 10); map.put(2, 8); Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); Integer key = (Integer) entry.getKey(); Integer value = (Integer) entry.getValue(); System.out.println(key + " ----- " + value); }
4. 通过key找value(效率低)
Map<Integer,Integer> map = new HashMap<>(); map.put(1, 10); map.put(2, 8); for ( Integer key : map.keySet()) { Integer value = map.get(key); System.out.println(key + " ----- " + value); }
List的遍历
1.方式一
List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); for ( Integer i : list) { System.out.println(i); }
2.方式二
List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); Iterator iterator = list.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); }
3.方式三
List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); for ( int i = 0 ; i < list.size() ; i++ ) { System.out.println(list.get(i)); }
时间: 2024-10-29 04:59:56