- import java.util.Collection;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- public class Test{
- public static void main(String[] args) {
- Map<String,Integer> map = new HashMap<String,Integer>();
- map.put("1", 1);
- map.put("2", 2);
- map.put("3", 3);
- map.put("4", 4);
- work(map);
- workByKeySet(map);
- workByEntry(map);
- }
- //最常规的一种遍历方法
- public static void work(Map<String, Integer> map) {
- Collection<Integer> c = map.values();
- Iterator it = c.iterator();
- for (; it.hasNext();) {
- System.out.print(it.next());
- }
- System.out.println();
- }
- //利用keyset进行遍历
- public static void workByKeySet(Map<String, Integer> map) {
- Set<String> key = map.keySet();
- for (Iterator it = key.iterator(); it.hasNext();) {
- String s = (String) it.next();
- System.out.print(map.get(s));
- }
- System.out.println();
- }
- //第三种
- public static void workByEntry(Map<String, Integer> map) {
- Set<Map.Entry<String, Integer>> set = map.entrySet();
- for (Iterator<Map.Entry<String, Integer>> it = set.iterator(); it.hasNext();) {
- Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) it.next();
- System.out.print("!!!!!" + entry.getKey() + "-------" + entry.getValue());
- }
- System.out.println();
- }
- }
复制代码 结果:
3214
3214
!!!!!3-------3!!!!!2-------2!!!!!1-------1!!!!!4-------4
|