日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

遍历map几种方式及应用

發布時間:2025/5/22 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 遍历map几种方式及应用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2019獨角獸企業重金招聘Python工程師標準>>>

Map<String, String> map = new HashMap<String, String>();
? map.put("1", "value1");
? map.put("2", "value2");
? map.put("3", "value3");
?
? //第一種:普遍使用,二次取值
? System.out.println("通過Map.keySet遍歷key和value:");
? for (String key : map.keySet()) {
?? System.out.println("key= "+ key + " and value= " + map.get(key));
? }
?
? //第二種
? System.out.println("通過Map.entrySet使用iterator遍歷key和value:");
? Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
? while (it.hasNext()) {
?? Map.Entry<String, String> entry = it.next();
?? System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
? }
?
? //第三種:推薦,尤其是容量大時
? System.out.println("通過Map.entrySet遍歷key和value");
? for (Map.Entry<String, String> entry : map.entrySet()) {
?? System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
? }

? //第四種
? System.out.println("通過Map.values()遍歷所有的value,但不能遍歷key");
? for (String v : map.values()) {
?? System.out.println("value= " + v);
? }

public class HashMapTest1
{
??? /**
???? * 找出一個數組中一個數字出現次數最多的數字
???? * 用HashMap的key來存放數組中存在的數字,value存放該數字在數組中出現的次數
???? * @author?guolz
???? */
??? public static void main(String[] args)
??? {
??????? int[] array = {2, 1, 2, 3, 4, 5, 2, 2, 2, 2};
????????
??????? //map的key存放數組中存在的數字,value存放該數字在數組中出現的次數
??????? HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
????????
??????? for(int i = 0; i < array.length; i++)
??????? {
??????????? if(map.containsKey(array[i]))
??????????? {
??????????????? int temp = map.get(array[i]);
????????????????
??????????????? map.put(array[i], temp + 1);
??????????? }
??????????? else
??????????? {
??????????????? map.put(array[i], 1);
??????????? }
??????? }
????????
??????? Collection<Integer> count = map.values();
????????
??????? //找出map的value中最大的數字,也就是數組中數字出現最多的次數
??????? int maxCount = Collections.max(count);
????????
??????? int maxNumber = 0;
????????
??????? for(Map.Entry<Integer, Integer> entry : map.entrySet())
??????? {
??????????? //得到value為maxCount的key,也就是數組中出現次數最多的數字
??????????? if(maxCount == entry.getValue())
??????????? {
??????????????? maxNumber = entry.getKey();
??????????? }
??????? }
????????
??????? System.out.println("出現次數最多的數字為:" + maxNumber);
??????? System.out.println("該數字一共出現" + maxCount + "次");
??? }
}

?

轉載于:https://my.oschina.net/u/1054538/blog/624838

總結

以上是生活随笔為你收集整理的遍历map几种方式及应用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。