本文主要是介绍map用法 keySet、entrySet、四种遍历,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
map用法
keySet、entrySet、四种遍历
Map<String,String> map = new HashMap<>();map.put("1","hello");map.put("2","world");map.put("3","!");Set<String> set = map.keySet();Set<Map.Entry<String, String>> s = map.entrySet();Iterator iterator = set.iterator();Iterator<Map.Entry<String, String>> i = s.iterator();while (iterator.hasNext()){System.out.println(iterator.next());}/*** entrySet是 java中 键-值 对的集合,实现了Set集合* Set里面的类型是Map.Entry* */Map<Integer,String> mapOf = new HashMap<>();mapOf.put(1,"hello");mapOf.put(2,"world");mapOf.put(3,"!");Set<Map.Entry<Integer,String>> set1 = mapOf.entrySet();Iterator<Map.Entry<Integer,String>> it = set1.iterator();//1while(it.hasNext()){Map.Entry<Integer,String> entry = it.next();int key = entry.getKey();String value = entry.getValue();System.out.println(key);System.out.println(value);}//2for(Map.Entry<Integer,String> entry : set1){int key = entry.getKey();String value = entry.getValue();System.out.println(key);System.out.println(value);}/** 推荐,尤其容量大时,同上 */for (Map.Entry<Integer,String> entry : mapOf.entrySet()){int key = entry.getKey();String value = entry.getValue();}//3/** 普遍使用,二次取值 */for (int key : mapOf.keySet()){String value = mapOf.get(key);}//4/** 通过Map.values()遍历所有的value,但不能遍历key */for (String v : mapOf.values()) {String value = v;}
这篇关于map用法 keySet、entrySet、四种遍历的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!