zoukankan      html  css  js  c++  java
  • 集合之map详解(遍历)

     

    14.判断List、Map、Set是否为空及效率比较:

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

    12、简单介绍Map

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

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

    14.判断List、Map、Set是否为空及效率比较:

    //如果object为null,则设置为defaultValue
    ObjectUtils.defaultIfNull(object, defaultValue);

    //判断集合是否为null
    List<String> list=new ArrayList<String>();
    System.out.println(list.isEmpty()); //true
    System.out.println(list.size()); //0

    Set<String> set=new HashSet<String>();
    System.out.println(set.isEmpty()); //true
    System.out.println(set.size()); //0

    Map<String, String> map=new HashMap<String, String>();
    System.out.println(map.isEmpty()); //true
    System.out.println(map.size()); //0

    方法一(数据量大,效率低):
    if(list!=null && list.size()>0){
    }

    方法二(数据量大,效率高):
    if(list!=null && !list.isEmpty()){
    }
     

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

    方法1: 通过 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());  
          
        }  
     
    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());  
          
        }  
     
     
    方法2、通过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);  
        }
     
     
     
    方法3、 如果只需要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));
        }
     
     
    全部代码:
        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.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

    12、简单介绍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

  • 相关阅读:
    Linux 下安装 mysql8
    Git 上传本地项目到Github
    vue+vscode+nodejs 开发环境搭建
    window下 局域网内使用mysql,mysql 开启远程访问权限
    spring boot application 配置详情
    spring boot starter列表
    【第一篇】spring boot 快速入门
    Spring中手动增加配置文件中占位符引用的变量
    spring容器
    springmvc细节篇
  • 原文地址:https://www.cnblogs.com/awkflf11/p/6385662.html
Copyright © 2011-2022 走看看