day23--Java集合06

来源:https://www.cnblogs.com/liyuelian/archive/2022/08/20/16608467.html
-Advertisement-
Play Games

Java集合06 13.Map介面02 13.2Map介面常用方法 put():添加 remove():根據鍵鍵刪除映射關係 get():根據鍵獲取值 size():獲取元素個數 isEnpty():判斷個數是否為0 clear():清除 containsKey():查找鍵是否存在 例子1:Map接 ...


Java集合06

13.Map介面02

13.2Map介面常用方法

  1. put():添加
  2. remove():根據鍵鍵刪除映射關係
  3. get():根據鍵獲取值
  4. size():獲取元素個數
  5. isEnpty():判斷個數是否為0
  6. clear():清除
  7. containsKey():查找鍵是否存在

例子1:Map介面常用方法

package li.map;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("all")
public class MapMethod {
    public static void main(String[] args) {
        Map map = new HashMap();
        // 1.put():添加
        map.put("羅貫中",new Book("111",99));//ok
        map.put("羅貫中","三國演義");//替換上一個value
        map.put("施耐庵","666");//ok
        map.put("克魯蘇","666");//ok
        map.put(null,"空空如也");//ok
        map.put("空空如也",null);//ok

        System.out.println(map);

        // 2.remove():根據鍵鍵刪除映射關係
        map.remove(null);
        System.out.println(map);//null對應的"空空如也"沒有了

        // 3. get():根據鍵獲取值,返回一個Object類型
        System.out.println(map.get("羅貫中"));//三國演義

        // 4. size():獲取k-v對數
        System.out.println(map.size());//4

        // 5. isEnpty():判斷個數是否為0
        System.out.println(map.isEmpty());//false

        // 6. clear():將所有k-v清空
        map.clear();
        System.out.println(map);//{}

        // 7. containsKey():查找鍵是否存在
        map.put("我是123","我是123的value");
        System.out.println(map.containsKey("我是123"));//true
    }
}
class Book{
    private String name;
    private int price;

    public Book(String name, int price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}
image-20220819192540298

13.3Map介面六大遍歷方式

  1. containsKey:查找鍵是否存在
  2. keySet:獲取所有的鍵
  3. entrySet:獲取所有的關係k-v
  4. values:獲取所有的值

例子:

package li.map;

import java.util.*;

@SuppressWarnings("all")
public class MapFor {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("羅貫中", new Book("111", 99));
        map.put("羅貫中", "三國演義");
        map.put("施耐庵", "666");
        map.put("克魯蘇", "666");
        map.put(null, "空空如也");
        map.put("空空如也", null);

        
        //第一組:先取出所有的key,通過key取出對應的value
        Set keySet = map.keySet();
        System.out.println("----增強for----");
        
        //增強for
        for (Object key : keySet) {
            System.out.println(key + "-" + map.get(key));//get():根據鍵獲取值
        }
        
        System.out.println("----迭代器----");
        //迭代器
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()) {
            Object key = iterator.next();
            System.out.println(key + "-" + map.get(key));
        }

        

        //第二組:把所有的values值取出
        Collection values = map.values();
        //這裡可以使用所有collection使用的遍歷方法
        
        //增強for:
        System.out.println("---取出所有的value 增強for---");
        for (Object value : values) {
            System.out.println(value);
        }
        
        //迭代器:
        System.out.println("---取出所有的value 迭代器:---");
        Iterator iterator2 = values.iterator();
        while (iterator2.hasNext()) {
            Object value = iterator2.next();
            System.out.println(value);
        }


        
        //第三組:通過EntrySet直接取出k-v對
        Set entrySet = map.entrySet();//EntrySet<Map.Entry<K,V>>
        
        //(1)增強for
        System.out.println("---使用EntrySet的增強for---");
        for (Object entry : entrySet) {
            //將entry轉成 Map.Entry
            Map.Entry m = (Map.Entry) entry;
            System.out.println(m.getKey()+"-"+m.getValue());
        }
        
        //(2)迭代器:
        System.out.println("---使用EntrySet的迭代器---");
        Iterator iterator3 = entrySet.iterator();
        while (iterator3.hasNext()) {
            Object entry =  iterator3.next();//這裡next取出來的類型本質上是Node,讓偶向上轉型為Object
            //System.out.println(next.getClass());//class java.util.HashMap$Node
            //向下轉型Object---> Map.Entry
            Map.Entry m = (Map.Entry)entry;
            System.out.println(m.getKey()+"-"+m.getValue());
        }

    }
}

13.4Map課堂練習

使用HashMap添加三個員工對象,要求:

鍵:員工id

值:員工對象

並遍歷顯示工資>18000的員工(遍歷方式最少兩種)

員工類:姓名、工資、員工id

練習:

package li.map;

import java.util.*;

@SuppressWarnings("all")
public class MapExercise {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put(1, new Employee("smith", 8800, 1));
        map.put(2, new Employee("John", 18900, 2));
        map.put(3, new Employee("Jack", 8900, 3));
        map.put(4, new Employee("Marry", 19900, 4));
        map.put(5, new Employee("Jack", 3000, 5));

        //keySet
        Set keySet = map.keySet();

        System.out.println("---keySet的增強for---");
        for (Object key : keySet) {
            Employee value = (Employee) map.get(key);//將獲得的value對象向下轉型為Employee類型
            double salary = value.getSalary();//獲取工資
            if (salary > 18000) {
                System.out.println(map.get(key));
            }//判斷輸出
        }

        System.out.println("---keySet的迭代器---");
        Iterator iterator = keySet.iterator();
        while (iterator.hasNext()) {
            Object key = iterator.next();
            Employee value = (Employee) map.get(key);//將獲得的value對象向下轉型為Employee類型
            double salary = value.getSalary();//獲取工資
            if (salary > 18000) {
                System.out.println(map.get(key));
            }//判斷輸出
        }


        //EntrySet
        Set entrySet = map.entrySet();
        System.out.println("---entrySet的增強for---");
        for (Object entry : entrySet) {//entry代表一對k-v
            //將entry向下轉型轉成 Map.Entry
            Map.Entry m = (Map.Entry) entry;
            Employee employee = (Employee) m.getValue();
            double salary = employee.getSalary();
            if (salary > 18000) {//判斷輸出
                System.out.println(m.getValue());
            }
        }

        System.out.println("---entrySet的迭代器---");
        Iterator iterator2 = entrySet.iterator();
        while (iterator2.hasNext()) {
            Object entry = iterator2.next();
            Map.Entry m = (Map.Entry) entry;//將Object強轉為Map.Entry類型
            Employee employee = (Employee) m.getValue();
            double salary = employee.getSalary();
            if (salary > 18000) {//判斷輸出
                System.out.println(m.getValue());
            }
        }
    }
}

class Employee {
    private String name;
    private double salary;
    private int id;

    public Employee(String name, double salary, int id) {
        this.name = name;
        this.salary = salary;
        this.id = id;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                ", id=" + id +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

13.5HashMap小結

  1. Map介面的常用實現類:HashMap、Hashtable、Properties
  2. HashMap是Map介面使用頻率最高的實現類
  3. HashMap是以key-value對的方式來存儲數據(HashMap$Node類型)
  4. key不能重覆,value可以重覆。允許使用null鍵和null值
  5. 如果添加相同的key鍵,則會覆蓋原來的key-value,等同於修改(key不會替換,value會替換)
  6. 與HashSet一樣,不保證映射的順序,因為底層是以hash表的順序來存儲的。(JDK8的HashMap底層:數組+鏈表+紅黑樹)
  7. HashMap沒有實現同步,因此線程不安全,方法沒有做同步互斥的操作,沒有synchronized

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1. 入門案例--hello spring 創建Maven Module 在pom.xml中引入依賴 <dependencies> <!-- 基於Maven依賴傳遞性,導入spring-context依賴即可導入當前所需所有jar包 --> <dependency> <groupId>org.spr ...
  • 原文: Java 斷點下載(下載續傳)服務端及客戶端(Android)代碼 - Stars-One的雜貨小窩 最近在研究斷點下載(下載續傳)的功能,此功能需要服務端和客戶端進行對接編寫,本篇也是記錄一下關於貼上關於實現服務端(Spring Boot)與客戶端(Android)是如何實現下載續傳功能 ...
  • “請你說一下你對Happens-Before的理解” 你聽到這個問題的時候,知道怎麼回答嗎? 大家好,我是Mic,一個工作了14年的Java程式員。 併發編程是面試過程中重點考察的方向,能夠考察的方向有很多 關於這個問題,我把高手回答整理到了15W字的面試文檔裡面大家可以私信我領取 下麵看看高手的回 ...
  • 序列類型的操作 遍歷 從第一個元素到最後一個元素依次訪問(序列類型) for i in 序列: print(i) # i是序列中的值(如果該序列為字典,那麼i為字典的鍵) for i in enumerate(序列): # enumerate(序列):講序列拆分成國歌元組(值,下標) print(i ...
  • 頂層const和底層const 變數自身不能改變的是頂層const,比如const int,int *const的常量指針,變數所指的對象或者所引用的對象是不能改變的,而變數自身是可以改變的是底層const,比如const int *的指向常量對象的非常量指針。 左值和右值 左值是有具體存儲地址的值 ...
  • mamp pro 是最優秀的本地伺服器搭配軟體,也是最好的mysql開發環境和php開發環境,包含了acintosh、Apache、MySQL和PHP四大開發環境,用戶只要輕鬆點選就能對架站、討論區、論壇等必備的元件進行安裝,讓你輕鬆架設自己的web運行環境。 Mac版詳情:MAMP Pro for ...
  • 文末有Gitee鏈接,記得star哦 課程整體內容概述 第一部分:編程語言核心結構 主要知識點:變數、基本語法、分支、迴圈、數組、 第二部分:Java面向對象的核心邏輯 主要知識點:OOP、封裝、繼承、多態、介面、 第三部分:開發JavaSE高級應用程式 主要知識點:異常、集合、|℃、多線程、反射機 ...
  • 目錄 一.簡介 二.效果演示 三.源碼下載 四.猜你喜歡 零基礎 OpenGL (ES) 學習路線推薦 : OpenGL (ES) 學習目錄 >> OpenGL ES 基礎 零基礎 OpenGL (ES) 學習路線推薦 : OpenGL (ES) 學習目錄 >> OpenGL ES 轉場 零基礎 O ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...