Java SEMap集合迭代方式
CAMELLIA!!! note 目录
Map集合迭代方式
修饰符和类型 |
方法 |
描述 |
Set<K> |
keySet() |
返回此映射中包含的键的 Set 视图。 |
static interface |
Map.Entry<K,V> |
映射条目(键值对)。 |
一、Map集合迭代方式一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| package com.camellia.map;
import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set;
public class MapIteration {
private static Map<Integer,String> maps = new HashMap<>();
static { maps.put(1,"CAMELLIA"); maps.put(2,"·"); maps.put(3,"XIAOHUA"); }
@Test public void testMapIteration1(){ Set<Integer> keys = maps.keySet(); Iterator<Integer> it = keys.iterator(); while (it.hasNext()){ Integer next = it.next(); System.out.println(next+"\t"+maps.get(next)); } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| package com.camellia.map;
import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set;
public class MapIteration {
private static Map<Integer,String> maps = new HashMap<>();
static { maps.put(1,"CAMELLIA"); maps.put(2,"·"); maps.put(3,"XIAOHUA"); }
@Test public void testMapIteration2(){ Set<Integer> keys = maps.keySet(); for (Integer key:keys){ System.out.println(key+"\t"+maps.get(key)); } } }
|
二、Map集合迭代方式二
这种方式效率比较高,推荐使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| package com.camellia.map;
import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set;
public class MapIteration {
private static Map<Integer,String> maps = new HashMap<>();
static { maps.put(1,"CAMELLIA"); maps.put(2,"·"); maps.put(3,"XIAOHUA"); }
@Test public void testMapIteration3(){ Set<Map.Entry<Integer, String>> entries = maps.entrySet(); Iterator<Map.Entry<Integer, String>> it = entries.iterator(); while (it.hasNext()){ Map.Entry<Integer, String> next = it.next(); System.out.println(next.getKey()+"\t"+next.getValue()); } } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| package com.camellia.map;
import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set;
public class MapIteration {
private static Map<Integer,String> maps = new HashMap<>();
static { maps.put(1,"CAMELLIA"); maps.put(2,"·"); maps.put(3,"XIAOHUA"); }
@Test public void testMapIteration4(){ for (Map.Entry<Integer, String> entry: maps.entrySet()){ System.out.println(entry.getKey()+"\t"+entry.getValue()); } } }
|
使用Set<Map.Entry<Integer, String>> entries = maps.entrySet();更高的原因是不用在通过key返回去再找value,减少了中间的包装。