概要:
Map 提供了一个更通用的元素存储方法。Map 集合类用于存储元素对(称作“键”和“值”),其中每个键映射到一个值。
本文主要介绍java map的初始化、用法、map的四种常用的遍历方式、map的排序以及常用api。
## 1Map用法
### 类型介绍
Java 自带了各种 Map 类。这些 Map 类可归为三种类型:
1\. 通用Map,用于在应用程序中管理映射,通常在 java.util 程序包中实现
HashMap、Hashtable、Properties、LinkedHashMap、IdentityHashMap、TreeMap、WeakHashMap、ConcurrentHashMap
2\. 专用Map,通常我们不必亲自创建此类Map,而是通过某些其他类对其进行访问
java.util.jar.Attributes、javax.print.attribute.standard.PrinterStateReasons、java.security.Provider、java.awt.RenderingHints、javax.swing.UIDefaults
3\. 一个用于帮助我们实现自己的Map类的抽象类
AbstractMap
### 类型区别
HashMap
最常用的Map,它根据键的HashCode 值存储数据,根据键可以直接获取它的值,具有很快的访问速度。HashMap最多只允许一条记录的键为Null(多条会覆盖);允许多条记录的值为 Null。非同步的。 | |
TreeMap | |
能够把它保存的记录根据键(key)排序,默认是按升序排序,也可以指定排序的比较器,当用Iterator 遍历TreeMap时,得到的记录是排过序的。TreeMap不允许key的值为null。非同步的。 | |
Hashtable | |
与 HashMap类似,不同的是:key和value的值均不允许为null;它支持线程的同步,即任一时刻只有一个线程能写Hashtable,因此也导致了Hashtale在写入时会比较慢。 | |
LinkedHashMap | |
保存了记录的插入顺序,在用Iterator遍历LinkedHashMap时,先得到的记录肯定是先插入的.在遍历的时候会比HashMap慢。key和value均允许为空,非同步的。 |
初始化数据
User user1 = new User(1, "A", "xx1", "xx2", "xx3"); | |
User user2 = new User(2, "B", "xx1", "xx2"); | |
User user3 = new User(3, "C", "xx1"); | |
User user4 = new User(4, "D", "xx1", "xx2", "xx3"); | |
List<User> list = new ArrayList<>(); | |
list.add(user1); | |
list.add(user2); | |
list.add(user3); | |
list.add(user4); | |
stream流分组取值
Map<String, Long> collect1 = list.stream().filter(s -> s.getCateOneId() != null).collect(Collectors.groupingBy(s -> s.getCateOneId(), Collectors.counting())); | |
System.out.println(collect1); | |
Integer counts = 0; | |
Iterator<Map.Entry<String, Long>> iterator = collect1.entrySet().iterator(); | |
while (iterator.hasNext()) { | |
Map.Entry<String, Long> entry = iterator.next(); | |
counts = entry.getValue().intValue(); | |
} | |
System.out.println(counts); | |
Map<String, Long> collect2 = list.stream().filter(s -> s.getCateTwoId() != null).collect(Collectors.groupingBy(s -> s.getCateTwoId(), Collectors.counting())); | |
System.out.println(collect2); | |
Map<String, Long> collect3 = list.stream().filter(s -> s.getCateThreeId() != null).collect(Collectors.groupingBy(s -> s.getCateThreeId(), Collectors.counting())); | |
System.out.println(collect3); | |
Iterator<Map.Entry<String, Long>> iterator2 = collect2.entrySet().iterator(); | |
while (iterator2.hasNext()){ | |
Map.Entry<String, Long> next = iterator2.next(); | |
int i = next.getValue().intValue(); | |
} |