hashMap的遍历和排序

Java hashMap的遍历和排序

思想:总的来说就是获得map的key或者value,放入到一个list中,对list进行排序,根据不同的排序需求实现不同Comparator接口。那么就得学习一下具体的遍历的方法,和具体怎么实现Comparator接口的。

遍历方法

比较常用的是通过entrySet去获取键值对。

  • 通过entrySet

    Map<Character,Integer> map=new HashMap<Character, Integer>();
            map.put('a',1);
            map.put('c',2);
            map.put('b',3);
    
            for (Map.Entry<Character,Integer> entry:map.entrySet()){
                Character key = entry.getKey();
                Integer value = entry.getValue();
                System.out.println(key+":"+value);
            }
    
  • KeySet

    通过map.keySet获取key

    通过map.values 获取value

  • 迭代器 EntrySet

    Iterator<Map.Entry<Character, Integer>> iterator = map.entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry<Character, Integer> next = iterator.next();
                Character key = next.getKey();
                Integer value = next.getValue();
                System.out.println(key+":"+value);
            }
    
  • Lambda

    map.forEach((key,value) -> {
        System.out.println(key);
        System.out.println(value);
    });
    
  • streams Api 单线程

    map.entrySet().stream().forEach(entry -> {
        System.out.println(entry.getKey()+":"+entry.getValue());
    });
    
  • streams Api 多线程

    map.entrySet().parallelStream().forEach(entry -> {
         System.out.println(entry.getKey()+":"+entry.getValue());
     });
    

排序

  • 按照value进行升序排列

    Map<Character,Integer> map=new HashMap<Character, Integer>();
            map.put('a',1);
            map.put('c',2);
            map.put('b',3);
    
            List<Map.Entry<Character,Integer>> list=new ArrayList<>();
            list.addAll(map.entrySet());
    
            Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
                @Override
                public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
                    return o1.getValue().compareTo(o2.getValue());
                }
            });
    
            System.out.println(list);
    
  • 降序排序

    lamaba表达式的o1和o2位置互换

  • 优先按值value降序、其次按键key升序排序

    public int compare(Map.Entry<String,Integer>e1,Map.Entry<String,Integer>e2){
                    int re = e2.getValue().compareTo(e1.getValue());
                    if(re!=0){return re;}
                    else{return e1.getKey().compareTo(e2.getKey());}
    
    
    
  • 4、优先按键key降序、其次按值value升序排序

public int compare(Map.Entry<String,Integer>e1,Map.Entry<String,Integer>e2){
                int re = e2.getKey().compareTo(e1.getKey());
                if(re!=0){return re;}
                else{return e1.getValue().compareTo(e2.getValue());}
            }

例题:字符统计_牛客题霸_牛客网 (nowcoder.com)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fb1lW8jB-1667548336704)(数据结构与算法.assets/image-20221104153603731.png)]

思路:hashMap 存储数据 key表示字符 value 表示字符出现的次数

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str = in.next();

            Map<Character, Integer> map = new HashMap<>();
            for (int i = 0; i < str.length(); i++) {
                int count = map.getOrDefault(str.charAt(i), 0);
                map.put(str.charAt(i), ++count);
            }

            List<Map.Entry<Character, Integer>> list = new ArrayList<>();
            list.addAll(map.entrySet());

            Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
                @Override
                public int compare(Map.Entry<Character, Integer> o1,
                                   Map.Entry<Character, Integer> o2) {
                    int re = o2.getValue().compareTo(o1.getValue());
                    if (re != 0) {
                        return re;
                    } else {
                        return o1.getKey().compareTo(o2.getKey());
                    }
                }
            });

            for(Map.Entry<Character,Integer> m:list){
                System.out.print(m.getKey());
            }

            
        }
    }
}

参考文章:

(60条消息) java中Map的七种遍历方法_童话ing的博客-CSDN博客

[(59条消息) Java 对HashMap 进行排序的几种场景_童话ing的博客-CSDN博客_java hashmap排序](https://blog.csdn.net/dl962454/article/details/110355513?ops_request_misc=&request_id=&biz_id=102&utm_term=java hashmap排序&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-5-110355513.nonecase&spm=1018.2226.3001.4187)

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值