Java map 详解 - 用法、遍历、排序、常用API等 Java map 详解 - 用法、遍历、排序、常用API等

概要:

java.util 中的集合类包含 Java 中某些最常用的类。最常用的集合类是 List 和 Map。

Map 提供了一个更通用的元素存储方法。Map 集合类用于存储元素对(称作“键”和“值”),其中每个键映射到一个值。

本文主要介绍java map的初始化、用法、map的四种常用的遍历方式、map的排序以及常用api。

1、Map用法

类型介绍

Java 自带了各种 Map 类。这些 Map 类可归为三种类型:

  1. 通用Map,用于在应用程序中管理映射,通常在 java.util 程序包中实现

HashMap、Hashtable、Properties、LinkedHashMap、IdentityHashMap、TreeMap、WeakHashMap、ConcurrentHashMap

  1. 专用Map,通常我们不必亲自创建此类Map,而是通过某些其他类对其进行访问

java.util.jar.Attributes、javax.print.attribute.standard.PrinterStateReasons、java.security.Provider、java.awt.RenderingHints、javax.swing.UIDefaults

  1. 一个用于帮助我们实现自己的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均允许为空,非同步的。

Map 初始化

Map map = new HashMap();

插入元素

map.put("key1", "value1");

获取元素

map.get("key1")

移除元素

map.remove("key1");

清空map

map.clear();

2、四种常用Map插入与读取性能比较

public class Test {
 static int hashMapW = 0;
 static int hashMapR = 0;
 static int linkMapW = 0;
 static int linkMapR = 0;
 static int treeMapW = 0;
 static int treeMapR = 0;
 static int hashTableW = 0;
 static int hashTableR = 0;
 
 public static void main(String[] args) {
 for (int i = 0; i < 10; i++) {
 Test test = new Test();
 test.test(100 * 10000);
 System.out.println();
 }
 
 System.out.println("hashMapW = " + hashMapW / 10);
 System.out.println("hashMapR = " + hashMapR / 10);
 System.out.println("linkMapW = " + linkMapW / 10);
 System.out.println("linkMapR = " + linkMapR / 10);
 System.out.println("treeMapW = " + treeMapW / 10);
 System.out.println("treeMapR = " + treeMapR / 10);
 System.out.println("hashTableW = " + hashTableW / 10);
 System.out.println("hashTableR = " + hashTableR / 10);
 }
 
 public void test(int size) {
 int index;
 Random random = new Random();
 String[] key = new String[size];
 
 // HashMap 插入
 Map map = new HashMap();
 long start = System.currentTimeMillis();
 for (int i = 0; i < size; i++) {
 key[i] = UUID.randomUUID().toString();
 map.put(key[i], UUID.randomUUID().toString());
 }
 long end = System.currentTimeMillis();
 hashMapW += (end - start);
 System.out.println("HashMap插入耗时 = " + (end - start) + "