Map的遍历与排序

素颜马尾好姑娘i 2022-04-22 07:40 241阅读 0赞

引言:集合是java比较重要的一个知识点,而集合的遍历尤为重要。
相对来说,Map又是集合中比较难懂的一部分,故今天来讲一下Map的
遍历与排序。

Map的遍历

  • 较为简单的遍历方法可以通过keySet()方法获取Map中的所有的key,
    然后使用get(key)获取key对应的value,代码如下:

    Map map = new HashMap();
    map.put(“1”,”xinger”);
    //······省略部分代码
    for(String s : map.keySet()){
    System.out.println(“key:”+s+”,”+”value:”+map.get(s));
    }

  • 通过Map.entrySet()遍历map:Map.entrySet()方法返回该地图的集合视图(Set(Map.Entry<K,V>))

    for(Map.Entry entry : map.entrySet()){ //参数类型请灵活处理
    System.out.println(“key:”+entry.getKey()+”,”+”value:”+entry.getValue());
    }

  • 通过迭代器遍历Map:

    Iterator(Map.Entry) ite = map.entrySet().iterator();
    while(ite.hasNext()){

    1. Map.Entry<String, String> entry = ite.next();
    2. System.out.println("key:"+entry.getKey()+","+"value:"+entry.getValue());z

    }

Map的排序

  • 利用TreeMap类进行排序:TreeMap是默认按key的升序排序,若要改变排序方式,需要使用比较器Comparator
    并使用构造器TreeMap(Comparator<? super K> comparator),注意到泛型? super K,故本质还是进行按key排序。

    Map map = new TreeMap(new Comparator(){

    1. @Override
    2. public int compare(String o1, String o2) {
    3. return o2.compareTo(p1);

    });

  • Map按value排序:实现Comparator接口,并重写compare(Object o1, Object o2)方法

    List> list = new ArrayList>(map.entrySet());

    1. //排序
    2. Collections.sort(list, new Comparator<Map.Entry<String, Integer>>(){ //内部类
    3. @Override
    4. public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
    5. return o2.getValue() - o1.getValue();
    6. }
    7. });

发表评论

表情:
评论列表 (有 0 条评论,241人围观)

还没有评论,来说两句吧...

相关阅读