Java容器——Map接口
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接口的更多相关文章
- Java容器Map接口
Map接口容器存放的是key-value对,由于Map是按key索引的,因此 key 是不可重复的,但 value 允许重复. 下面简单介绍一下Map接口的实现,包括HashMap,LinkedHas ...
- JAVA ,Map接口 ,迭代器Iterator
1. Map 接口概述 java.util.Map 接口描述了映射结构, Map 接口允许以键集.值集合或键 - 值映射关系集的形式查看某个映射的内容. Java 自带了各种 Map 类. 这些 ...
- Java集合Map接口与Map.Entry学习
Java集合Map接口与Map.Entry学习 Map接口不是Collection接口的继承.Map接口用于维护键/值对(key/value pairs).该接口描述了从不重复的键到值的映射. (1) ...
- Java Core - Map接口
Map:是一组映射The java.util.Map interface represents a mapping between a key and a value. The Map interfa ...
- java中map接口hashMap以及Enty之间的用法和关系
java中map接口hashMap以及Enty之间的转换 首先说的是map接口: Map提供了一种映射关系,其中的元素是以键值对(key-value)的形式存储的,能够实现根据key快速查找value ...
- Java之Map接口(双列集合)
Map集合概述 现实生活中,我们常会看到这样的一种集合:IP地址与主机名,身份证号与个人,系统用户名与系统用户对象等,这种一一对应的关系,就叫做映射.Java提供了专门的集合类用来存放这种对象关系的对 ...
- Java 之 Map 接口
一.Map 接口概述 java.util.Map 接口专门用来存放键值对这种对象关系的对象. 下面比较一下 Collection 与 Map 的区别: Collection 中的集合,元素是孤立存在的 ...
- Java集合——Map接口
1.定义 Map用于保存存在映射关系<key,value>的数据.其中,key值不能重复(使用equals()方法比较),value值可以重复 2.方法 V put(key,value) ...
- Java API —— Map接口
1.Map接口概述 · 将键映射到值的对象 · 一个映射不能包含重复的键 · 每个键最多只能映射到一个值 2.Map接口和Collection接口的 ...
随机推荐
- c++继承、多态以及与java的行为差异之处
对于面向对象而言,多态是最有用的基本特性之一,相对于函数指针,易用得多.下面看下c++继承和多态行为的基本特性,最后说明下和java的基本差别. 首先定义父类和子类. base.h #pragma o ...
- 04: 打开tornado源码剖析处理过程
目录:Tornado其他篇 01: tornado基础篇 02: tornado进阶篇 03: 自定义异步非阻塞tornado框架 04: 打开tornado源码剖析处理过程 目录: 1.1 torn ...
- Linux中tomcat日志按日期自动分割
Linux中tomcat日志分割需要用到cronolog 附上cronolog-1.6.2.tar.gz 1. 安装cronolog tar –zxvf cronolog-1.6.2.tar.gz . ...
- 20145310 《网络对抗》 MSF基础应用
实验要求 掌握metasploit的基本应用方式,掌握常用的三种攻击方式的思路. 一个主动攻击,如ms08_067; 一个针对浏览器的攻击,如ms11_050: 一个针对客户端的攻击,如Adobe 成 ...
- 如何高效判断java数组是否包含某个值
在java中,我们如何判断一个未排序数组中是否包含一个特定的值?这在java中是一个频繁非常实用的操作.那么什么样的方法才是最高效的方式?当然 ,这个问题在Stack Overflow也是得票率非常高 ...
- assert函数用法总结【转】
本文转载自:http://blog.csdn.net/u014082714/article/details/45190505 assert宏的原型定义在<assert.h>中,其作用是如果 ...
- 手机常用meta标签-有注释
<!-- 设置字体编码 --> <meta charset="UTF-8"> <!-- 视图窗口,移动端特属的标签. --> <meta ...
- Gym - 100345H Settling the Universe Up(bitset)
https://vjudge.net/problem/Gym-100345H 题意: 给出一个图,求图中u能到达v的对数,并且u<v.并且会有更新和查询操作. 思路: bitset直接暴力,对于 ...
- HDU 6072 Logical Chain(Kosaraju+bitset)
http://acm.hdu.edu.cn/showproblem.php?pid=6072 题意: 给你$n*n$的矩阵,每次修改k条边,让你计算其中能相互到达的点对有多少. 思路: 其实就是求强连 ...
- CRLF line terminators导致shell脚本报错:command not found --转载
Linux和Windows文本文件的行结束标志不同.在Linux中,文本文件用"/n"表示回车换行,而Windows用"/r/n"表示回车换行.有时候在Wind ...