13、简单介绍Map

12、Map排序(TreeMap的key排序,TreeMap的value排序;HashMap的value排序;)

11.map集合的6种遍历方式 

=============

2、简单介绍Map

map是键值对的集合接口,它的实现类主要包括:HashMap,TreeMap,Hashtable以及LinkedHashMap等。
--HashMap:
非同步的。最常用的Map,它根据key的HashCode 值来存储数据,根据key可以直接获取它的Value,同时它具有很快的访问速度。
HashMap最多只允许一条记录的key值为Null(多条会覆盖);允许多条记录的Value为 Null。

--TreeMap:
非同步的。能够把它保存的记录根据key排序,默认是按升序排序,也可以指定排序的比较器,当用Iterator 遍历TreeMap时,得到的记录是排过序的。TreeMap不允许key的值为null。

--Hashtable:
类似HashMap,不同的是:key和value的值均不允许为null;它支持线程的同步,即任一时刻只有一个线程能写Hashtable,因此也导致了Hashtale在写入时会比较慢。

--LinkedHashMap:
非同步的。保存了记录的插入顺序,在用Iterator遍历LinkedHashMap时,先得到的记录肯定是先插入的,在遍历的时候会比HashMap慢。key和value均允许为空。

1、Map排序(TreeMap的key排序,TreeMap的value排序;HashMap的value排序;)

---1.1,TreeMap--TreeMap的key排序;
TreeMap默认是升序的,如果我们需要改变排序方式,则需要使用比较器:Comparator。

Comparator可以对集合对象或者数组进行排序的比较器接口,实现该接口的public compare(T o1,To2)方法即可实现排序,
该方法主要是根据第一个参数o1,小于、等于或者大于o2分别返回负整数、0或者正整数。

public class TreeMapTest {
public static void main(String[] args) {
Map<String, String> map = new TreeMap<String, String>(
new Comparator<String>() {
public int compare(String obj1, String obj2) {
// 降序排序
return obj2.compareTo(obj1);
}
});
map.put("c", "ccccc");
map.put("a", "aaaaa");
map.put("b", "bbbbb");
map.put("d", "ddddd");

Set<String> keySet = map.keySet();
Iterator<String> iter = keySet.iterator();
while (iter.hasNext()) {
String key = iter.next();
System.out.println(key + ":" + map.get(key));
}
}
}
运行结果如下:
d:ddddd
c:ccccc
b:bbbbb
a:aaaaa
上面例子是对根据TreeMap的key值来进行排序的,但是有时我们需要根据TreeMap的value来进行排序。

---1.2,TreeMap的value排序
对value排序我们借助于Collections的sort(List<T> list, Comparator<? super T> c)方法,该方法根据指定比较器产生的顺序对指定列表进行排序。但是有一个前提条件,那就是所有的元素都必须能够根据所提供的比较器来进行比较。

public class TreeMapTest {
public static void main(String[] args) {
Map<String, String> map = new TreeMap<String, String>();
map.put("d", "ddddd");
map.put("b", "bbbbb");
map.put("a", "aaaaa");
map.put("c", "ccccc");

//这里将map.entrySet()转换成list
List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
//然后通过比较器来实现排序
Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
//升序排序
public int compare(Entry<String, String> o1,Entry<String, String> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});

for(Map.Entry<String,String> mapping:list){
System.out.println(mapping.getKey()+":"+mapping.getValue());
}
}
}
运行结果
a:aaaaa
b:bbbbb
c:ccccc
d:ddddd

1.3,HashMap--HashMap的value排序;

我们都是HashMap的值是没有顺序的,他是按照key的HashCode来实现的。对于这个无序的HashMap我们要怎么来实现排序呢?
参照TreeMap的value排序,我们一样的也可以实现HashMap的value排序。

public class HashMapTest {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("c", "ccccc");
map.put("a", "aaaaa");
map.put("b", "bbbbb");
map.put("d", "ddddd");

List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
//升序排序
public int compare(Entry<String, String> o1,Entry<String, String> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});

for(Map.Entry<String,String> mapping:list){
System.out.println(mapping.getKey()+":"+mapping.getValue());
}
}
}
运行结果
a:aaaaa
b:bbbbb
c:ccccc
d:ddddd

11.map集合的6种遍历方式 ?

方法一 通过Map.entrySet遍历key和value,在for-each循环中使用entries来遍历.推荐,尤其是容量大时
这是最常见的并且在大多数情况下也是最可取的遍历方式。在键值都需要时使用。
使用map的entrySet()方法返回一个以Entry为元素的Set集合,然后对Set集合进行遍历。
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
      
    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {  
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
      
    }  
方法二、通过Map.keySet遍历key,通过键找值value遍历(效率低),普遍使用,二次取值.
使用keyset方法遍历,是先取出map的key组成的Set集合,通过对Set集合的遍历,然后使用map.get(key)方法取出value值。
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
      
    for (Integer key : map.keySet()) {  
        Integer value = map.get(key);  
        System.out.println("Key = " + key + ", Value = " + value);  
    }
方法三、 如果只需要map中的键或者值,你可以通过Map.keySet或Map.values来实现遍历,而不是用entrySet。在for-each循环中遍历keys或values。
map.values()返回的是由map的值组成的Collection,这个方法只能遍历map的所有value,不能得到map的key。
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
      
    //遍历map中的键  
    for (Integer key : map.keySet()) {  
        System.out.println("Key = " + key);  
    }  
      
    //遍历map中的值  
    for (Integer value : map.values()) {  
        System.out.println("Value = " + value);  
    }  
4. 通过keySet()返回的集合的iterator遍历
由于map.keySet()返回的是一个Set集合,所以通过它的iterator()方法返回一个迭代器,通过迭代器遍历map。
    Iterator<String> it = map.keySet().iterator();
    while(it1.hasNext()) {
        String key = it1.next();
        System.out.println(key + " : " + map.get(key));
    }
5. 通过values()返回的Collection的iterator遍历
map.values()方法返回的是一个Collection对象,这个集合对象可以使用iterator方法访问。
    Iterator<String> it = map.values().iterator();
    while(it.hasNext()) {
        String key = it1.next();
        System.out.println(key + " : " + map.get(key));
    }
6.通过Map.entrySet返回的Set的iterator 遍历key和value
 同上,map.entrySet()方法返回的是一个Set<Entry<String, String»类型的集合,可以使用iterator来访问该集合。
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
      
    Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();  
      
    while (it.hasNext()) {  
      
        Map.Entry<Integer, Integer> entry = it.next();  
    
        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
      
    }  
全部代码:
    public static void main(String[] args) {
            init();
            traversal();
        }
    
        // HashMap按照哈希算法来存取键对象,有很好的存取性能
        private static HashMap<String, String> hMap = new HashMap<>();
    
        // TreeMap实现了SortedMap接口,能对键对象进行排序。支持自然排序和客户化排序两种方式。
        private static TreeMap<String, String> tMap = new TreeMap<>();
    
        // map的赋值
        public static void init() {
            hMap.put("1", "value1");
            hMap.put("2", "value2");
            hMap.put("3", "value3");
        }
    
        // map的遍历
        public static void traversal() {
            // 第一种:普遍使用,二次取值
            System.out.println("通过Map.keySet遍历key和value:");
            for (String key : hMap.keySet()) {
                System.out.println("key= " + key + " and value= " + hMap.get(key));
            }
    
            // 第二种
            System.out.println("通过Map.entrySet使用iterator遍历key和value:");
            Iterator<Map.Entry<String, String>> it = hMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> entry = it.next();
                System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
            }
    
            // 第三种:推荐,尤其是容量大时
            System.out.println("通过Map.entrySet遍历key和value");
            for (Map.Entry<String, String> entry : hMap.entrySet()) {
                System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
            }
    
            // 第四种
            System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
            for (String v : hMap.values()) {
                System.out.println("value= " + v);
            }
        }
运行结果:
通过Map.keySet遍历key和value:
key= 1 and value= value1
key= 2 and value= value2
key= 3 and value= value3
通过Map.entrySet使用iterator遍历key和value:
key= 1 and value= value1
key= 2 and value= value2
key= 3 and value= value3
通过Map.entrySet遍历key和value
key= 1 and value= value1
key= 2 and value= value2
key= 3 and value= value3
通过Map.values()遍历所有的value,但不能遍历key
value= value1
value= value2
value= value3

集合之map详解(遍历)的更多相关文章

  1. List、Set、Map详解及区别

    一.List接口 List是一个继承于Collection的接口,即List是集合中的一种.List是有序的队列,List中的每一个元素都有一个索引:第一个元素的索引值是0,往后的元素的索引值依次+1 ...

  2. Sass map详解

    作为一个CSS预处理器,Sass正受到越来越多的青睐,诸如Github.Codepen.CSS-Tricks.SitePoint.w3cplus等网站采用Sass组织.管理CSS文件,Sass正在逐渐 ...

  3. 【Java集合】LinkedList详解前篇

    [Java集合]LinkedList详解前篇 一.背景 最近在看一本<Redis深度历险>的书籍,书中第二节讲了Redis的5种数据结构,其中看到redis的list结构时,作者提到red ...

  4. java中list和map详解

    一.概叙 List , Set, Map都是接口,前两个继承至Collection接口,Map为独立接口, List下有ArrayList,Vector,LinkedList Set下有HashSet ...

  5. 源映射(Source Map)详解

    一.什么是源映射 为了提高性能,很多站点都会先压缩 JavaScript 代码然后上线, 但如果代码运行时出现错误,浏览器只会显示在已压缩的代码中的位置,很难确定真正的源码错误位置. 这时源映射就登场 ...

  6. 集合框架的详解,List(ArrayList,LinkedList,Vector),Set(HashSet,TreeSet)-(14)

    集合详解: /* Collection |--List:元素是有序的,元素可以重复.因为该集合体系有索引. |--ArrayList:底层的数据结构使用的是数组结构.特点:查询速度很快.但是增删稍慢. ...

  7. 集合框架学习之Collection和Map详解

    线性表,链表,哈希表是常用的数据结构,在进行Java开发时,JDK已经为我们提供了一系列相应的类来实现基本的数据结构.这些类均在java.util包中.本文试图通过简单的描述,向读者阐述各个类的作用以 ...

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

    尊重原创: http://www.cnblogs.com/lzq198754/p/5780165.html 概要: java.util 中的集合类包含 Java 中某些最常用的类.最常用的集合类是 L ...

  9. Java集合-----Map详解

          Map与Collection并列存在.用于保存具有映射关系的数据:Key-Value      Map 中的 key 和  value 都可以是任何引用类型的数据      Map 中的 ...

随机推荐

  1. Can’t call setState (or forceUpdate) on an unmounted component 警告处理方法

    Can’t call setState (or forceUpdate) on an unmounted component Warning: Can't call setState (or forc ...

  2. SharePoint Online 使用 adal js 获取access token

    最近在写一些SharePoint 的sample code, 有兴趣的小伙伴可以查看我的GitHub. 今天给大家介绍SharePoint Framework (SPFx  )web part 当中怎 ...

  3. 用Python免费发短信,实现程序实时报警

    进入正文 今天跟大家分享的主题是利用python库twilio来免费发送短信. 先放一张成品图: 代码放在了本文最后的地址中 正文 眼尖的小伙伴已经发现了上面的短信的前缀显示这个短信来自于一个叫Twi ...

  4. Meandering Through the Maze of MFC Message and Command Routing MFC消息路由机制分析

    Meandering Through the Maze of MFC Message and Command Routing Paul DiLascia Paul DiLascia is a free ...

  5. PyCharm中的Console自动换行

    菜单栏-> File -> Settings -> Editor -> General -> Console,选中右侧Use soft wraps in console前 ...

  6. C++ Builder使用VC DLL

    好久没用BCB了,真的有些陌生了,当然个烂笔头吧. 1 先 implib c:\xxx.lib c:\xxx.dll 生成lib文件 2 #pragma comment(lib,"xxx.l ...

  7. 基于spring的placeholder思路处理配置信息敏感信息加密解密的实践

    基于Spring的placeholder处理思路,实现系统配置信息敏感信息的加密解密处理. 我们的处理方案,是基于类org.springframework.beans.factory.config.P ...

  8. mac里安装Mycrypt扩展

    https://jingyan.baidu.com/article/e3c78d644cf1ed3c4c85f5a8.html 先用homebrew安装mycrpt 再下载php5.6版本源码 然后进 ...

  9. minicom的安装及配置

    1. sudo apt-get install minicom 2. 配置 (1). sudo minicom –s (2). (3). 按“A”配置设备,再按回车保存.按”F”,把留空改为NO.回车 ...

  10. [转]阿里云CentOS 7.1使用yum安装MySql5.6.24

    阿里云CentOS 7.1使用yum安装MySql5.6.24 作者:vfhky | 时间:2015-06-25 09:43 | 分类:web 在前面两篇文章<2015博客升级记(四):Cent ...