- package exam;
- import java.util.Collection;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Set;
- public class MapTest {
- public static void main(String[] args) {
- HashMap<String, Integer> map = new HashMap<String,Integer>(20);
- map.put("a", 1);
- map.put(null, 2);
- map.put("h", null);
- // Entry_bianli(map);
- // Key_value(map);
- // FenBieBianLi(map);
- fanXing(map);
- }
- //使用map.entrySet().iterator进行遍历
- static public void Entry_bianli(Map map)
- {
- Iterator<Map.Entry<String, Integer>> ite = map.entrySet().iterator();
- while(ite.hasNext())
- {
- Map.Entry<String, Integer> entry = ite.next();
- System.out.println(entry.getKey()+" "+entry.getValue());
- }
- }
- //分别遍历出map的key和value
- static public void Key_value(Map map)
- {
- Set keyset = map.keySet();
- Iterator ite = keyset.iterator();
- while(ite.hasNext())
- {
- Object key = ite.next();
- System.out.println("key = "+key+" value = "+map.get(key));
- }
- }
- //获取map的keySet,foreach获取key,然后通过map.get(key)找到value
- static public void FenBieBianLi(Map map)
- {
- Set key = map.keySet();
- Collection value = map.values();
- for(Object ob : key)
- {
- System.out.println(ob);
- }
- for(Object ob : value)
- {
- System.out.println(ob);
- }
- }
- //获取map.entrySet(注意返回的是类型为Entry的Set),之后foreach遍历set,然后对每一项使用entry的getKey
- //和getValue方法.
- static public void fanXing(Map map)
- {
- Set<Entry<String,Integer>> set = map.entrySet();
- for(Entry<String,Integer> entry:set)
- {
- System.out.println(entry.getKey()+" "+entry.getValue());
- }
- }
- }
hashmap的四种遍历方法
最新推荐文章于 2024-08-28 00:39:43 发布