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学习笔记之递归和迭代的区别

    电影故事例证:迭代——<明日边缘>递归——<盗梦空间> 迭代是更新变量的旧值.递归是在函数内部调用自身. 迭代是将输出做为输入,再次进行处理.比如将摄像头对着显示器:比如镜子对 ...

  2. loj10009 P1717 钓鱼

    P1717 钓鱼 贪心+优先队列 先枚举最后走到哪个湖,然后用优先队列跑一遍贪心即可 #include<iostream> #include<cstdio> #include& ...

  3. tf.reduce_sum tensorflow维度上的操作

    tensorflow中有很多在维度上的操作,本例以常用的tf.reduce_sum进行说明.官方给的api reduce_sum( input_tensor, axis=None, keep_dims ...

  4. python2.7+pyqt4 +eric4安装配置

    eric4安装与汉化一直没找到合适python的IDE工具,直到遇到了eric4这款开源软件.然而在使用过程中发现输出的中文字符竟然是乱码,修修改改配置总算正常显示了,何不干脆把软件界面也汉化下. 一 ...

  5. Leading and Trailing(数论/n^k的前三位)题解

    Leading and Trailing You are given two integers: n and k, your task is to find the most significant ...

  6. 移动端Css初始化

    @charset "utf-8"; /* 禁用iPhone中Safari的字号自动调整 */ html { -webkit-text-size-adjust: %; -ms-tex ...

  7. C# WinCE项目 VS2008 单例窗体实现

    项目现有主界面FormMain,模板界面FormModel,其余5个子界面皆继承自模板. 现在想要实现在主界面下可以打开任意子界面,并且可以随时关闭.当打开的子窗体未执行Close事件时,要保证每次显 ...

  8. ASCII 、UTF-8、Unicode都是个啥啊,为啥会乱码啊?

    因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理.最早的计算机在设计时采用8个比特(bit)作为一个字节(byte),所以,一个字节能表示的最大的整数就是255(二进制1111 ...

  9. mark一下总是记混的重定向与转发的区别

    forward内部跳转 和redirect重定向跳转的区别 1).从地址栏显示来说  forward是服务器请求资源,服务器直接访问目标地址的URL,把那个URL的响应内容读取过来,然后把这些内容再发 ...

  10. UI自动化测试篇 :webdriver+ant+jenkins自动化测试实践

    http://www.cnblogs.com/chengtch/p/6063360.html 前面基本弄清楚了webdriver+ testng 的测试环境部署,现在这里记录一下结合ant及jenki ...