zoukankan      html  css  js  c++  java
  • java中map按值排序的方法

    在学习的过程中,遇到一个问题,类似于TreeMap<String,Set<String>>,要求按照Set集合中集合的个数来对map中的key进行排序。下面说一下解决方法,由于自己新手方法可能有点笨,但是能够解决这样的问题。大体的思想就是遍历现有的map,将其复制到一个新的map中,注意复制的过程中将key和值进行调换,这样对于新的map的排序就是按照原来的值进行的排序。最后再将新的map中的数据复制到原来的map中问题就解决了。下面附上代码:

    public static List<String> influencers(Map<String, Set<String>> followsGraph) {
    TreeMap<Set<String>,String> newfollow = new TreeMap<Set<String>,String>(
    new Comparator<Set<String>>() {
    public int compare(Set<String> o1, Set<String> o2) {
    int num = o2.size()-o1.size();
    int num2 = num == 0?o2.toString().compareTo(o1.toString()):num;
    return num2;
    }
    }
    );
    List<String> result = new ArrayList<>();
    for(String key : followsGraph.keySet()) {
    Set<String> value = new TreeSet<>();
    value = followsGraph.get(key);
    newfollow.put(value, key);
    }
    for(Set<String> key : newfollow.keySet()) {
    result.add(newfollow.get(key));
    }
    return result;
    }

  • 相关阅读:
    rust中的arm交叉编译
    Dockerfile简单编写
    docker常用命令
    linux下tf/u盘格式化
    rust查看支持的架构列表
    linux内核版本修改
    cgo引用外部c文件注意1
    redis服务允许外部ip访问开启
    redis密码修改
    setInterval和setTimeout的使用区别
  • 原文地址:https://www.cnblogs.com/mrchi/p/8622430.html
Copyright © 2011-2022 走看看