java -- Map介面和可變參數

来源:https://www.cnblogs.com/paopaoT/archive/2023/04/11/17307413.html
-Advertisement-
Play Games

Kafka 環境搭建 kafka 安裝、配置、啟動、測試說明: 1. 安裝:直接官網下載安裝包,解壓到指定位置即可(kafka 依賴的 Zookeeper 在文件中已包含) 下載地址:https://kafka.apache.org/downloads 示例版本:kafka_2.13-2.8.0.t ...


Map

Map: 映射, 是雙列集合頂層介面
java.util.Map<k,v>
k: key 鍵 唯一
v: value 值 可重覆

常用方法和Entry

public V put(K key,V Value)
// 指定的鍵與指定值添加到Map集合中, 添加成功返回null, 添加失敗返回之前的值
public V putIfAbsent(K key,V Value)
// jdk1.8後新增 鍵相同值不覆蓋返回原來的值

public V get(Object key)
// 根據指定的鍵, 獲取對應值, 不存在返回null
public V getOrDefault(Object key, V defaultValue)
// jdk1.8後新增 不存在返回defaultValue

public boolean containsKey(Object key)
// 判斷集合中是否包含指定的鍵

public V remove(Object key)
// 根據指定的鍵, 刪除一對元素, 返回被刪除的值
public V remove(Object key, Object value)
// 根據指定的鍵和值, 都一致則刪除, 返回被刪除的值

Set<K> keySet()
// 獲取存放所有鍵的Set集合
Collection<V> values()
// 獲取存放所有值的集合

Set<Map.Entry<K, V>> entrySet()
// 獲取鍵值對映射關係對象的Set集合


interface Entry<K,V>
K getKey()
// 獲取映射關係對象中的鍵
V getValue()
// 獲取映射關係對象中的值

LinkedHashMap

底層數據結構: 鏈表 + 哈希表
鏈表保證元素有序 哈希表保證元素唯一

public class Demo {
    public static void main(String[] args) {
        Map<String, Integer> map = new LinkedHashMap<>();

        map.put("1張三",14);
        map.put("2李四",17);
        // put
        // 添加成功返回 null
        System.out.println(map.put("3王五", null));
        // 添加失敗返回之前的值, 並用新值覆蓋
        System.out.println(map.put("2李四", 19));

        // putIfAbsent
        // 鍵不存在添加新的鍵值對, 添加成功返回null
        System.out.println(map.putIfAbsent("4劉六", 19));
        // 若鍵存在 原有值不改變 並返回原有值
        System.out.println(map.putIfAbsent("1張三", 11));

        // get
        // 根據鍵找值, 存在則返回鍵對應的值
        System.out.println(map.get("1張三"));
        // 不存在則返回null
        System.out.println(map.get("2"));

        // getOrDefault
        // 鍵存在 返回對應值
        System.out.println(map.getOrDefault("1張三", -1));
        // 若不存在 則返回defaultValue
        System.out.println(map.getOrDefault("2", -1));

        // 判斷集合中是否包含指定的鍵, 存在返回true, 不存在返回false
        System.out.println(map.containsKey("2李四"));

        // 根據鍵刪除一對元素 返回被刪除的值
        // 不存在則返回null
        System.out.println(map.remove("1"));
        System.out.println(map.remove("1張三"));

        System.out.println(map);

        // 遍歷
        // 方式1
        // 獲取存放所有鍵的集合
        Set<String> set = map.keySet();
        // 獲取存放所有值的集合
        Collection<Integer> values = map.values();

        // 迭代器
        Iterator<Integer> iterator = values.iterator();
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
        System.out.println();
        // 增強for
        for (Integer value : values) {
            System.out.print(value + " ");
        }
        System.out.println();

        // 迭代器
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String key = it.next();
            System.out.print(key + " = " + map.get(key) + "\t");
        }
        System.out.println();
        // 增強for
        for (String s : set) {
            System.out.print(s + " = " + map.get(s) + "\t");
        }
        System.out.println();

        // 方式2
        // Entry是Map的內部類 所以調用時需要Map.Entry
        Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
        // 迭代器
        Iterator< Map.Entry<String, Integer>> entries = entrySet.iterator();
        while (entries.hasNext()) {
            Map.Entry<String, Integer> next = entries.next();
            System.out.print(next.getKey() + " = " + next.getValue() + "\t");
        }
        System.out.println();
        // 增強for
        for (Map.Entry<String, Integer> entry : entrySet) {
            System.out.print(entry.getKey() + " = "+entry.getValue() + "\t");
        }
    }
}

TreeMap

java.util.TreeMap
底層數據結構是紅黑樹 鍵 排序 具有唯一性 不允許null鍵 允許null值

/*
    java.util.TreeMap
        底層數據結構是紅黑樹  鍵 排序 具有唯一性  不允許null鍵 允許null值
        構造方法:
            public TreeMap() 空參構建, 集合中的鍵必須實現自然排序介面 Comparable 的方法 CompareTo
            public TreeMap(Comparator<? super K> comparator) 需傳入比較器對象
 */
public class Demo {
    public static void main(String[] args) {
        TreeMap<Person, String> map = new TreeMap<>();
        map.put(new Person("張三",12),"bj");
        map.put(new Person("張三",14),"sh");
        map.put(new Person("李四",15),null);
        map.put(new Person("王五",11),"gz");
        map.put(new Person("宮本",19),"jp");
        // 不允許null鍵
        // map.put(null,"us");
        System.out.println(map);
        // 獲取第一個鍵
        System.out.println(map.firstKey());
        // 獲取最後一個鍵
        System.out.println(map.lastKey());
        // 獲取第一個鍵值對
        System.out.println(map.firstEntry());
        // 獲取最後一個鍵值對
        System.out.println(map.lastEntry());
        // 獲取 按排序方法 取索引 >= 指定鍵的最小鍵(>=指定鍵並距離最近)
        System.out.println(map.ceilingKey(new Person("李四", 13)));
        // 獲取 按排序方法 取索引 >= 指定鍵的最小鍵值對(>=指定鍵並距離最近)
        System.out.println(map.ceilingEntry(new Person("李四", 13)));
        // 獲取 按排序方法 取索引 <= 指定鍵的最小鍵(<=指定鍵並距離最近)
        System.out.println(map.floorKey(new Person("李四", 13)));
        // 獲取 按排序方法 取索引 <= 指定鍵的最小鍵值對(<=指定鍵並距離最近)
        System.out.println(map.floorEntry(new Person("李四", 13)));
        System.out.println("=================");

        TreeMap<Person, String> treeMap = new TreeMap<>(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                if (o1.age == o2.age) {
                    return o2.name.compareTo(o1.name);
                }
                return o1.age - o2.age;
            }
        });
        treeMap.put(new Person("張三",12),"bj");
        treeMap.put(new Person("張三",14),"sh");
        treeMap.put(new Person("李四",15),null);
        treeMap.put(new Person("王五",11),"gz");
        treeMap.put(new Person("宮本",19),"jp");
        System.out.println(treeMap);


    }
}


class Person implements Comparable<Person> {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Person o) {
        if (o.age == this.age) {
            return o.name.compareTo(this.name);
        }
        return o.age - this.age;
    }

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

HashMap

/*
    java.util.HashMap
        底層數據結構是哈希表 允許null鍵和null值  鍵是無序的 具有唯一性
        先比較hashCode
            不同 元素不相同
            相同 繼續比較equals
                相同
                不同
        因此必須重寫hashCode和equals方法
 */
public class Demo {
    public static void main(String[] args) {
        Map<Person, String> map = new HashMap<Person, String>();
        map.put(new Person("張三",12),"bj");
        map.put(new Person("李四",12),"sh");
        map.put(new Person("王五",12),"gz");
        map.put(new Person("宮本",12),"jp");
        map.put(null,"us");

        Set<Person> peopleSet = map.keySet();
        for (Person person : peopleSet) {
            if (person == null) {
                System.out.println(person + " " + map.get(person));
                continue;
            }
            System.out.println(person.getName() + " " + person.getAge() + " " + map.get(person));
        }

        Set<Map.Entry<Person, String>> entries = map.entrySet();
        for (Map.Entry<Person, String> entry : entries) {
            Person key = entry.getKey();
            if (key == null) {
                System.out.println(key + " " + entry.getValue());
                continue;
            }
            System.out.println(key.getName() + " "+ key.getAge() + " "+entry.getValue());
        }

    }

}
class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        if (age != person.age) return false;
        return name != null ? name.equals(person.name) : person.name == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}

可變參數

JDK1.5之後,如果我們定義一個方法需要接受多個參數,並且多個參數類型一致,我們可以對其簡化.

// 格式
修飾符 返回值類型 方法名(參數類型... 形參名){  }
/*
    可變參數 指參數的個數可變
        當參數數據類型確定,且需要較多次重載時, 可以使用可變參數
        可變參數必須放在參數列表的最後, 且只能有一個可變參數
        格式: 本質上就是數組
            public static int avg(int... nums)
            當不傳入參數時, 相當於傳了空數組
            由於本質是數組, 因此傳入數組也可以
*/
public class function {
    public static void main(String[] args) {

        System.out.println(avg(1,2,3,4,5,7,8,9,2));
        System.out.println(avg(18,9,2));
        System.out.println(avg(1,2));
        int[] arr = {1,23,42,45,34,21};
        System.out.println(avg(arr));
    }

    public static int avg(int... nums) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
        }
        return sum / nums.length;
    }
}

練習

使用Map重寫前天第十一題

使用54張牌打亂順序,三個玩家參與游戲,三人交替摸牌,每人17張牌,最後三張留作底牌.

import java.util.*;

public class PokerDemo {
    public static void main(String[] args) {
        Map<Integer, String> pokerMap = new HashMap<Integer, String>();
        ArrayList<Integer> pokerIndex = new ArrayList<Integer>();
        String[] colors = {"♥","♠","♣","♦"};
        String[] numbers = "2-A-K-Q-J-10-9-8-7-6-5-4-3".split("-");
        int index = 2;
        pokerMap.put(0, "大王");
        pokerMap.put(1, "小王");
        for (String number : numbers) {
            for (String color : colors) {
                pokerMap.put(index, color+number);
                index++;
            }
        }

        for (int i = 0; i < 54; i++) {
            pokerIndex.add(i);
        }
        Collections.shuffle(pokerIndex);

        ArrayList<Integer> player1 = new ArrayList<Integer>();
        ArrayList<Integer> player2 = new ArrayList<Integer>();
        ArrayList<Integer> player3 = new ArrayList<Integer>();
        ArrayList<Integer> dipai = new ArrayList<Integer>();

        for (int i = 0; i < pokerIndex.size(); i++) {
            if (i >= 51){
                dipai.add(pokerIndex.get(i));
            } else if (i % 3 == 0) {
                player1.add(pokerIndex.get(i));
            } else if (i % 3 == 1) {
                player2.add(pokerIndex.get(i));
            } else {
                player3.add(pokerIndex.get(i));
            }
        }

        System.out.println("玩家1: " + showPoker(player1, pokerMap));
        System.out.println("玩家2: " + showPoker(player2, pokerMap));
        System.out.println("玩家3: " + showPoker(player3, pokerMap));
        System.out.println("底牌: " + showPoker(dipai, pokerMap));
    }
    public static String showPoker(ArrayList<Integer> player, Map<Integer, String> pokerMap) {
        Collections.sort(player);
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < player.size(); i++) {
            sb.append(pokerMap.get(player.get(i)));
            if (i == player.size() - 1) {
                sb.append("]");
            } else {
                sb.append(", ");
            }
        }
        return sb.toString();
    }
}


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

-Advertisement-
Play Games
更多相關文章
  • 前言 監控指標誠然是發現問題於微末之時的極佳手段,但指標往往有其表達的極限。在很多情況下,單獨看一個黃金指標並不能表徵系統的健康程度,反而有可能被其迷惑,進而忽略相關問題。(本文所提及的Linux Kernel源碼版本為4.18.10) Bug現場 某天中午,某應用的999線突然升高。由於是個QPS ...
  • 經典設計模式源碼詳解,用不同語言來實現,包括Java/JS/Python/TypeScript/Go等。結合實際場景,充分註釋說明,每一行代碼都經過檢驗,確保可靠。 設計模式是一個程式員進階高級的必然選擇,不懂設計模式,就像寫文章不懂得層次,蓋房子沒有結構。只有充分懂得設計之道,才能真正設計出良好的... ...
  • 本文轉載自國外論壇 medium,原文地址: https://medium.com/navan-tech/7-java-features-you-might-not-have-heard-of-adee8166d942,由博主簡譯後給大家帶來! Show me your code and I wil ...
  • 前言 在上一篇文章中,我們介紹了&運算符的高級用法,本篇文章,我們將介紹| 運算符的一些高級用法。 一、人物簡介 第一位閃亮登場,有請今後會一直教我們C語言的老師 —— 自在。 第二位上場的是和我們一起學習的小白程式猿 —— 逍遙。 二、將兩個位元組合併成一個16位整數 #include <stdio ...
  • 最近互聯網行業一片哀嘆,這是受到三年影響的後遺症,許多的公司也未能挺過寒冬,一些外資也開始撤出市場,因此許多的IT從業人員加入失業的行列,而且由於公司較少導致許多人求職進度緩慢,很不幸本人也是其中之一。自從參加工作以來,一直都是忙忙碌碌,開始總認為工作只是為了更好的生活,但是一旦工作停下來後自己就覺 ...
  • 註意,該項目為Python基礎語法的一個綜合,項目資料庫。 #學員管理系統 """ 學員管理系統 1. 系統簡介 需求:進入系統顯示系統功能界面,功能如下: 1、添加學員 2、刪除學員 3、修改學員信息 4、查詢學員信息 5、顯示所有學員信息 6、退出系統 系統共6個功能,用戶根據自己需求選取。 " ...
  • 昨天出現一個生產問題。我們的channel系統代碼里,調用其中一個三方服務商的http介面時未設置超時時間。碰巧昨天出現一筆http請求持續數小時始終無響應,加之程式是單線程處理交易請求,就出現因為線程一直處於RUNNABLE狀態而導致系統生產能力嚴重下降。 現在說這個結論很easy,而昨天排查這個 ...
  • 1.struct 簡單介紹 struct 是 Python 的內置模塊, 在使用 socket 通信的時候, 大多數據的傳輸都是以二進位流的形式的存在, 而 struct 模塊就提供了一種機制, 該機制可以將某些特定的結構體類型打包成二進位流的字元串然後再網路傳輸,而接收端也應該可以通過某種機制進行 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...