Map的遍历和Map的有序和无序

简介: Map的遍历和Map的有序和无序

另:HashMap是无序的


Map<String, List> listMap = new LinkedHashMap<String, List>();//有序的


Map<Integer, String> map = new HashMap<Integer, String>();

8 map.put(1, “a”);

9 map.put(2, “b”);

10 map.put(3, “ab”);

11 map.put(4, “ab”);

12 map.put(4, “ab”);// 和上面相同 , 会自己筛选

13 System.out.println(map.size());

14 // 第一种:

15 /*

16 * Set set = map.keySet(); //得到所有key的集合

17 *

18 * for (Integer in : set) { String str = map.get(in);

19 * System.out.println(in + " " + str); }

20 */

21 System.out.println(“第一种:通过Map.keySet遍历key和value:”);

22 for (Integer in : map.keySet()) {

23 //map.keySet()返回的是所有key的值

24 String str = map.get(in);//得到每个key多对用value的值

25 System.out.println(in + " " + str);

26 }

27 // 第二种:

28 System.out.println(“第二种:通过Map.entrySet使用iterator遍历key和value:”);

29 Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

30 while (it.hasNext()) {

31 Map.Entry<Integer, String> entry = it.next();

32 System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());

33 }

34 // 第三种:推荐,尤其是容量大时

35 System.out.println(“第三种:通过Map.entrySet遍历key和value”);

36 for (Map.Entry<Integer, String> entry : map.entrySet()) {

37 //Map.entry<Integer,String> 映射项(键-值对) 有几个方法:用上面的名字entry

38 //entry.getKey() ;entry.getValue(); entry.setValue();

39 //map.entrySet() 返回此映射中包含的映射关系的 Set视图。

40 System.out.println("key= " + entry.getKey() + " and value= "

41 + entry.getValue());

42 }

43 // 第四种:

44 System.out.println(“第四种:通过Map.values()遍历所有的value,但不能遍历key”);

45 for (String v : map.values()) {

46 System.out.println("value= " + v);

47 }


相关文章
|
3月前
|
Go
go语言中遍历映射(map)
go语言中遍历映射(map)
99 8
Map遍历的几种方法
Map遍历的几种方法
|
9月前
Collection和Map的遍历方式
Collection和Map的遍历方式
51 0
|
9月前
|
测试技术
你知道几种遍历map的方式?
你知道几种遍历map的方式?
106 0
|
2月前
|
存储 缓存 安全
只会“有序无序”?面试官嫌弃的List、Set、Map回答!
小米,一位热衷于技术分享的程序员,通过与朋友小林的对话,详细解析了Java面试中常见的List、Set、Map三者之间的区别,不仅涵盖了它们的基本特性,还深入探讨了各自的实现原理及应用场景,帮助面试者更好地准备相关问题。
71 20
|
2月前
|
Go
go语言for遍历映射(map)
go语言for遍历映射(map)
75 12
|
3月前
|
存储 Go
go语言 遍历映射(map)
go语言 遍历映射(map)
57 2
|
4月前
|
前端开发 小程序 Java
java基础:map遍历使用;java使用 Patten 和Matches 进行正则匹配;后端传到前端展示图片三种情况,并保存到手机
这篇文章介绍了Java中Map的遍历方法、使用Pattern和matches进行正则表达式匹配,以及后端向前端传输图片并保存到手机的三种情况。
49 1
|
7月前
|
JavaScript API
js【最佳实践】遍历数组的八种方法(含数组遍历 API 的对比)for,forEach,for of,map,filter,reduce,every,some
js【最佳实践】遍历数组的八种方法(含数组遍历 API 的对比)for,forEach,for of,map,filter,reduce,every,some
137 1
|
8月前
|
缓存 Java 测试技术
探讨Java中遍历Map集合的最快方式
探讨Java中遍历Map集合的最快方式
128 1