Java基础 HashMap的添加 修改 遍历 Map.Entry Map.entrySet()的使用及实例
生活随笔
收集整理的這篇文章主要介紹了
Java基础 HashMap的添加 修改 遍历 Map.Entry Map.entrySet()的使用及实例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java Map
Map中不能包含相同的鍵,每個鍵只能映射一個值。
HashMap:并不能保證它的元素的順序,元素加入散列映射的順序并不一定是它們被迭代方法讀出的順序。
- Map.Entry
Map.Entry 是Map中的一個接口,他的用途是表示一個映射項(里面有Key和Value)
Map.Entry里有相應的getKey和getValue方法,即JavaBean,讓我們能夠從一個項中取出Key和Value。
- Map.entrySet()
Map.entrySet() 這個方法返回的是一個Set<Map.Entry<K,V>>。Set里面的類型是Map.Entry,里面存放的是鍵值對。一個K對應一個V。
- Map.keyset()
keySet是鍵的集合,Set里面的類型即key的類型。
package Map.test;import java.util.*;public class Test {public static void main(String args[]) {// 創建HashMap 對象HashMap hm = new HashMap();// 加入元素到HashMap 中hm.put("John Doe", new Double(3434.34));hm.put("Tom Smith", new Double(123.22));hm.put("Jane Baker", new Double(1378.00));hm.put("Todd Hall", new Double(99.22));hm.put("Ralph Smith", new Double(-19.08));// 返回包含映射項的集合Set set = hm.entrySet();// 用Iterator 得到HashMap 中的內容Iterator i = set.iterator();// 顯示元素while (i.hasNext()) {// Map.Entry 可以操作映射的輸入Map.Entry me = (Map.Entry) i.next();System.out.print(me.getKey() + ": ");System.out.println(me.getValue());}System.out.println();// 讓John Doe 中的值增加1000double balance = ((Double) hm.get("John Doe")).doubleValue();//得到舊值// 用新的值替換舊的值hm.put("John Doe", new Double(balance + 1000));System.out.println("John Doe's 現在的資金:" + hm.get("John Doe"));} } /* Todd Hall: 99.22 John Doe: 3434.34 Ralph Smith: -19.08 Tom Smith: 123.22 Jane Baker: 1378.0John Doe's 現在的資金:4434.34 *///四種遍歷Map public static void main(String[] args) {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);}} 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Java基础 HashMap的添加 修改 遍历 Map.Entry Map.entrySet()的使用及实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java rsa算法_求RSA算法JAV
- 下一篇: typescript索引类型_types