1.定义

Map用于保存存在映射关系<key, value>的数据。其中key值不能重复(使用equals()方法比较),value值可以重复。

2.常用实现类

HashMap:和HashSet类似,键按键的HashCode()方法确定存储位置,无序

TreeMap:用于对键进行排序,方式与TreeSet相同

LinkedHashMap:和LinkedHashSet类似

3.方法

3.1 HashMap常用方法

void clear():移除所有映射

Object clone():浅拷贝原映射

boolean containsKey(Object key):判断是否包含指定键

boolean containsValue(Object value):判断是否包含指定值

Set<Map.Entry<K,V>> entrySet():返回包含映射关系的set集合

V get(Object key):查找给定键的值

boolean isEmpty():判断是否为空

Set<K> keySet():返回map中键的set集合

V put(K key, V value):存入键值对

V putIfAbsent(K key, V value):存入键值对,如果该键未存在map中

V remove(Object key):移除给定键的键值对

boolean remove(Object key, Object value):移除给定的键值对

V replace(K key, V value):替换给定键的值

boolean replace(K key, V oldValue, V newValue):如果键值对符合要求,替换新值

int size():返回键值对数目

Collection<V> values():返回value集合

注:Map接口没有继承Iterable接口,所以不能直接通过map.iterator进行遍历(List,Map拥有该接口,可以直接遍历),需要先转化为set类型,使用entrySet()方法,Map.Entry<k,v>中含有方法getKey()和getValue(),获取对应的键和值。

4.示例

MapFunc.java

 import java.util.*;

 public class MapFunc {
public static void main(String[] args) { HashMap<String, Customer> hm1 = new HashMap<>();
hm1.put("a", new Customer(1,"AA"));
hm1.put("b", new Customer(2,"BB"));
hm1.put("c", new Customer(3,"CC"));
hm1.put("d", new Customer(4,"DD"));
hm1.put("e", new Customer(5,"EE")); /*
* Map的几种遍历方法
* keySet、values、entrySet、entrySet.iterator
* */
// 利用keySet()遍历
Set<String> keys = hm1.keySet();
System.out.println("keys= "+ keys); // [a, b, c, d]
for(String key: keys){
System.out.println("key= "+ key + " and value= " + hm1.get(key));
} // 利用values()遍历,无法遍历key
Collection<Customer> values = hm1.values();
System.out.println("values= "+ values); // [Customer:[Id=1, Name=AA],...]
for(Customer cus: values){
System.out.println("value= " + cus);
} // 利用entrySet遍历
Set<Map.Entry<String,Customer>> entries = hm1.entrySet();
System.out.println("entries= "+ entries); // [a=Customer:[Id=1, Name=AA],...]
for(Map.Entry<String, Customer> entry: entries){
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
} // 利用entrySet().iterator()遍历
Iterator<Map.Entry<String, Customer>> it = hm1.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Customer> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
} /*
* HashMap常用方法示例
* */
// get
Customer b = hm1.get("b");
System.out.println(b); // Customer:[Id=2, Name=BB] // putIfAbsent, key值存在,不覆盖value
hm1.putIfAbsent("e",new Customer(5,"EEE"));
System.out.println(hm1); // containsKey
boolean flag = hm1.containsKey("b");
System.out.println(flag); // true // containsValue
flag = hm1.containsValue(b);
System.out.println(flag); // remove
hm1.remove("c");
System.out.println(hm1); // Customer:[Id=3, Name=CC]
flag = hm1.remove("b", new Customer(1,"BB"));
System.out.println(flag); // false // replace
hm1.replace("b", new Customer(2,"BBB"));
System.out.println(hm1);
hm1.replace("d",new Customer(4,"D"),
new Customer(4,"DDD")); // 注意!!!
System.out.println(hm1); // clone
HashMap<String, Customer> hm2 = (HashMap<String, Customer>)hm1.clone();
System.out.println(hm2);
// clear
hm2.clear();
System.out.println(hm2); // {}
System.out.println(hm1);
// isEmpty
flag = hm2.isEmpty();
System.out.println(flag); // true
// size
int size = hm1.size();
System.out.println(size); // }
}

Customer.java

 import java.util.Objects;

 public class Customer implements Comparable<Customer>{

     private int customerId;
private String customerName; public Customer(Integer customerId, String customerName) {
this.customerId = customerId;
this.customerName = customerName;
} public int getCustomerId() {
return customerId;
}
public String getCustomerName() {
return customerName;
} @Override
public String toString() {
return "Customer:[Id=" + customerId + ", Name=" + customerName + "]";
} /*
* 重写compareTo方法
* 按Id或者name排序
* 可以对整体添加负号决定升降序
* */
@Override
public int compareTo(Customer o) {
// return this.customerId - o.customerId;
return this.customerName.compareTo(o.customerName);
} /*
* 重写equals和hashcode方法
* 这里id和name相同则为同一对象
* */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Customer)) return false;
Customer customer = (Customer) o;
return customerId == customer.customerId &&
Objects.equals(customerName, customer.customerName);
} @Override
public int hashCode() {
return Objects.hash(customerId, customerName);
} }

CustomerComparator.java

 import java.util.Comparator;

 public class CustomerComparator implements Comparator<Customer> {

     @Override
public int compare(Customer c1, Customer c2) {
// 按Id排序
return c1.getCustomerId() - c2.getCustomerId();
}
}

!!!

Java容器——Map接口的更多相关文章

  1. Java容器Map接口

    Map接口容器存放的是key-value对,由于Map是按key索引的,因此 key 是不可重复的,但 value 允许重复. 下面简单介绍一下Map接口的实现,包括HashMap,LinkedHas ...

  2. JAVA ,Map接口 ,迭代器Iterator

    1.    Map 接口概述 java.util.Map 接口描述了映射结构, Map 接口允许以键集.值集合或键 - 值映射关系集的形式查看某个映射的内容. Java 自带了各种 Map 类. 这些 ...

  3. Java集合Map接口与Map.Entry学习

    Java集合Map接口与Map.Entry学习 Map接口不是Collection接口的继承.Map接口用于维护键/值对(key/value pairs).该接口描述了从不重复的键到值的映射. (1) ...

  4. Java Core - Map接口

    Map:是一组映射The java.util.Map interface represents a mapping between a key and a value. The Map interfa ...

  5. java中map接口hashMap以及Enty之间的用法和关系

    java中map接口hashMap以及Enty之间的转换 首先说的是map接口: Map提供了一种映射关系,其中的元素是以键值对(key-value)的形式存储的,能够实现根据key快速查找value ...

  6. Java之Map接口(双列集合)

    Map集合概述 现实生活中,我们常会看到这样的一种集合:IP地址与主机名,身份证号与个人,系统用户名与系统用户对象等,这种一一对应的关系,就叫做映射.Java提供了专门的集合类用来存放这种对象关系的对 ...

  7. Java 之 Map 接口

    一.Map 接口概述 java.util.Map 接口专门用来存放键值对这种对象关系的对象. 下面比较一下 Collection 与 Map 的区别: Collection 中的集合,元素是孤立存在的 ...

  8. Java集合——Map接口

    1.定义 Map用于保存存在映射关系<key,value>的数据.其中,key值不能重复(使用equals()方法比较),value值可以重复 2.方法 V  put(key,value) ...

  9. Java API —— Map接口

    1.Map接口概述         · 将键映射到值的对象         · 一个映射不能包含重复的键         · 每个键最多只能映射到一个值   2.Map接口和Collection接口的 ...

随机推荐

  1. Python Web学习笔记之TCP的3次握手与4次挥手过程

    前言 尽管TCP和UDP都使用相同的网络层(IP),TCP却向应用层提供与UDP完全不同的服务.TCP提供一种面向连接的.可靠的字节流服务. 面向连接意味着两个使用TCP的应用(通常是一个客户和一个服 ...

  2. bzoj 1010 玩具装箱toy -斜率优化

    P教授要去看奥运,但是他舍不下他的玩具,于是他决定把所有的玩具运到北京.他使用自己的压缩器进行压缩,其可以将任意物品变成一堆,再放到一种特殊的一维容器中.P教授有编号为1...N的N件玩具,第i件玩具 ...

  3. Spark样本类与模式匹配

    一.前言 样本类(case class)与模式匹配(pattern matching)是Scala中一个比较复杂的概念,往往让人感觉深陷泥沼.我在这里对Scala中的样本类与模式匹配进行了一些整理,希 ...

  4. JQuery使用教程

    jQuery简介 jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team jQuery是对原生JavaScript二次封装的工具函数集合 ...

  5. 将kali linux装入U盘 制作随身携带的kali linux

    一 准备工作 USB3.0 U盘 不小于32G USB2.0的U盘安装速度要比3.0的慢一倍以上,运行也会有明显差别,所以建议使用3.0U盘.安装好之后差不多就得占用十几G,所以16G的太小了,尽量用 ...

  6. BZOJ 3339 && luogu4137 Rmq Problem / mex(莫队)

    P4137 Rmq Problem / mex 题目描述 有一个长度为n的数组{a1,a2,-,an}.m次询问,每次询问一个区间内最小没有出现过的自然数. 输入输出格式 输入格式: 第一行n,m. ...

  7. WannaflyCamp 平衡二叉树(DP)题解

    链接:https://www.nowcoder.com/acm/contest/202/F来源:牛客网 题目描述 平衡二叉树,顾名思义就是一棵“平衡”的二叉树.在这道题中,“平衡”的定义为,对于树中任 ...

  8. Ubuntu 下 su:authentication failure的解决办法

    Ubuntu下使用 su 切换到超级用户时候遇到下面的问题 su: Authentication failure 解决办法: $ sudo passwd root Enter new UNIX pas ...

  9. Spring 入门 web.xml配置详解

    Spring 入门 web.xml配置详解 https://www.cnblogs.com/cczz_11/p/4363314.html https://blog.csdn.net/hellolove ...

  10. Selenium 对窗口对HTML的操作举例