zoukankan      html  css  js  c++  java
  • Java从入门到放弃18---Map集合/HashMap/LinkedHashMap/TreeMap/集合嵌套/Collections工具类常用方法

    Java从入门到放弃18—Map集合/HashMap/LinkedHashMap/TreeMap/集合嵌套/Collections工具类常用方法
    01 Map集合
    Map集合处理键值映射关系的数据
    为了方便处理键值映射关系的数据,Java提供了一种Map集合
    键值映射关系的数据(一个键对应一个值,如一个学号对应一个学生)
    在双列集合中,所有的数据结构只和key有关,和value无关。键相同时,会覆盖value。
    基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。
    1
    2
    3
    4
    Map接口和Collection接口的区别
    Map接口和Collection接口的不同
    Map是双列的,Collection是单列的
    Map的键唯一,Collection的子体系Set是唯一的
    Map集合的数据结构针对键有效,跟值无关;Collection集合的数据结构是针对元素有效
    1
    2
    3
    4
    Map的常用方法
    通过put(key,value);方法添加元素
    通过clear();清楚集合
    通过get(key);根据键获取值
    通过remove(key);根据键移除这一组键值映射关系的数据
    通过keySet();获取所有键的set集合
    通过values();获取所有值的collection集合
    通过entrySet();返回一个键值对的set集合
    通过containsKey(key);判断集合中有没有键key
    通过containsValue(values);判断集合中有没有值values
    通过isEmpty();判断集合是否为空
    通过size();获取集合中的键值对的对数
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    Map的遍历
    //方式1:键找值
    public class Test{
    public static void main(String[] args){
    HashMap<Integer,String> hashMap=new HashMap<>();
    hashMap.put(1,"a");
    hashMap.put(2,"b");
    hashMap.put(3,"c");
    Set<Integer> keys=hashMap.keySet();
    for(Integer i :keys){
    System.out.println(i+"|"+hashMap.get(i));
    }
    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    //方式2:通过entrySet();获取键值对象Entry,用set集合接收;再遍历Entry。Entry提供了getKey()和getValve方法分别获取键值。Entry重写了toString方法,打印的是对象的内容而不是地址值。
    public class Test{
    public static void main(String[] args){
    HashMap<Integer,String> hashMap=new HashMap<>();
    hashMap.put(1,"a");
    hashMap.put(2,"b");
    hashMap.put(3,"c");
    Set<Map.Entry<Integer, String>> entries = hashMap.entrySet();
    for (Map.Entry<Integer, String> entry : entries) {
    //System.out.println(entry);
    Integer key = entry.getKey();
    String value = entry.getValue();
    System.out.println(key+"==="+value);
    }
    }
    }
    ---------------------

  • 相关阅读:
    html页面特效代码大全
    ASP.NET中个文件夹功能
    A project with an Output Type of Class Library cannot be started directly
    Chapter10“I/O设备的同步和异步”之I/O设备同步操作
    c c++ 文件操作
    linux find 文件夹下查找字符串
    c c++ sizeof
    c socket编程
    c fcntl函数
    read write 返回值
  • 原文地址:https://www.cnblogs.com/hyhy904/p/10930589.html
Copyright © 2011-2022 走看看