简体   繁体   English

按列表值对Java Map进行排序

[英]Sorting Java Map by List values

I need to sort a map by values using sorted method with map and lambda expression as arguments, while map has structure like: 我需要使用以map和lambda表达式作为参数的排序方法,通过值对地图进行排序,而map的结构如下:

Map<T,List<T>>=
Groovy = [Z, Y, X, D]
Java = [V, B, C, D, A, Z]
C++ = [G, J, H]
C# = [P, S, Q, V, D]
Scala = [A, D]

My sorted method: 我的排序方法:

sorted(Map<T,List<T>> map,Comparator<Map<T,List<T>>> comp)  

and then implement it in another function responsible for reading data from file and putting it into map. 然后在另一个负责从文件读取数据并将其放入地图的功能中实现它。 This is my sorted method: 这是我的排序方法:

public Map<T,List<T>> sorted(Map<T,List<T>> map, Comparator<Map<T,List<T>>> comp){
    List list = new LinkedList(map.entrySet());
    Collections.sort(list, comp);
    HashMap sortedHashMap = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
         sortedHashMap.put(entry.getKey(), entry.getValue());
    } 
    return sortedHashMap;
  }

And this is how I have used it in another method: 这就是我在另一种方法中使用它的方式:

Comparator<Map<T,List<T>>> comp = new Comparator() {
        public int compare(Object o1, Object o2) {
            return ((Comparable) ((Map.Entry) (o1)).getValue())
               .compareTo(((Map.Entry) (o2)).getValue());
         }};
iniMap=sorted(iniMap,comp);

When I run my program I get following error: 当我运行程序时,出现以下错误:

java.lang.ClassCastException: java.util.LinkedList cannot be cast to    java.lang.Comparable

Any help would be appreciated, I am kind of stuck. 任何帮助将不胜感激,我有点卡住。

Yes, the LinkedList class (as and any List / Collection subclass) doesn't implement the Comparable interface, so you will get the exception at runtime. 是的, LinkedList类(以及任何List / Collection子类)未实现Comparable接口,因此您将在运行时获取异常。

(1) You'd better think up your own comparison algorithm with T s rather than using incorrect casting with Object s: (1)您最好用T考虑自己的比较算法,而不是对Object使用不正确的转换:

Comparator<List<T>> comparator = (l1, l2) -> l1.size() - l2.size();

(2) Avoid raw types, try to generalize all code: (2)避免使用原始类型,请尝试归纳所有代码:

HashMap sortedHashMap = new LinkedHashMap();
       |
       V
HashMap<List<T>, T> map = new LinkedHashMap<>();

(3) Turn the anonymous class into a lambda expression. (3)将匿名类转换为lambda表达式。

(4) If you want to sort a map by values ( List<T> ), the comparator also should be appropriate: (4)如果要按值( List<T> )对映射进行排序,则比较器也应该合适:

Comparator<Map<T,List<T>>> c
       |
       V
Comparator<List<T>> c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM