0

我有一个 TreeMap,其中存储了一些值。地图使用值从最高到最低进行排序。现在我想打印出带有各种索引的 TreeMap 的内容。

如果我在地图中有以下对:

("Andrew", 10),
("John", 5),
("Don",9),
("Rolex", 30),
("Jack", 10),
("Dan",9)

我想打印出来:

Rolex, 30 , 1
Jack, 10, 2
Andrew, 10, 2
Dan, 9, 4
Don, 9, 4
John, 5, 6.

这是我一直在尝试的,但似乎效果不佳:

/**
 *
 * @author Andrew
 */

import java.util.*;

public class SortArray {

    static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>>entriesSortedByValues(Map<K,V> map) {
        SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
                new Comparator<Map.Entry<K,V>>() {
                    @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                         int res = e1.getValue().compareTo(e2.getValue());
                        return res!= 0 ? res : 1;
                        //return e1.getValue().compareTo(e2.getValue());
                    }
                });
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
    }



    public void test(){
        Map mm = new TreeMap();
        mm.put("Andrew", 11);
        mm.put("Mbata", 21);
        mm.put("Chinedu", 14);
        mm.put("Bol", 14);
        mm.put("Don", 51);
        mm.put("Rolex", 16);
        mm.put("Son", 41);
        SortedSet newMap =  entriesSortedByValues(mm);
        Iterator iter = newMap.iterator();
        int x = newMap.size();
        List names = new ArrayList();
        List scores = new ArrayList();
        while(iter.hasNext()){
            String details = iter.next().toString();
            StringTokenizer st = new StringTokenizer(details, "=");
            String name = st.nextToken();
            names.add(name);
            String score = st.nextToken();
            scores.add(score);
            //System.out.println(name + " Score:" +score + " Position:" + x);
            x--;
        }
        Collections.reverse(names);
        Collections.reverse(scores);
        int pos = 1;

        for(int i = 0; i<names.size();){
            try{
                int y = i+1;
                if(scores.get(i).equals(scores.get(y))){
                    System.out.print("Name: "+ names.get(i)+"\t");
                    System.out.print("Score: "+ scores.get(i)+"\t");
                    System.out.println("Position: "+ String.valueOf(pos));
                    //pos++;
                    i++;
                    continue;
                } else{
                    System.out.print("Name: "+ names.get(i)+"\t");
                    System.out.print("Score: "+ scores.get(i)+"\t");
                    System.out.println("Position: "+ String.valueOf(pos++));
                }
                i++;

            } catch(IndexOutOfBoundsException e) {}
        }
    }

    public SortArray(){
        test();
    }

    public static void main(String [] args){
        new SortArray();
    }
}
4

3 回答 3

0

SortedSet的做法是错误的。您可以在您的文章中看到,Comparator当必须通过同一个键查找两个值时,它会变得有点混乱,然后您就会变得混乱(并且不正确)return res != 0 ? res : 11实际上应该是e1.getKey().compareTo(e2.getKey())而不是总是返回1)。

解决此问题的更好方法是自己在 a 中对键进行排序List,而不是创建单独的SortedSet. 这样您就不必担心重复的排序值。

如果需要,您还可以稍微抽象一下这些Comparator东西,以便以后在其他代码中更可重用。

import java.util.*;

public class PrintSomething {
    public static <T extends Comparable<T>> Comparator<T> reverseComparator(final Comparator<T> oldComparator) {
        return new Comparator<T>() {
            @Override
            public int compare(T o1, T o2) {
                return oldComparator.compare(o2, o1);
            }
        };
    }

    public static <K,V extends Comparable<V>> Comparator<K> keyedComparator(final Map<K,V> lookup) {
        return new Comparator<K>() {
            @Override
            public int compare(K o1, K o2) {
                return lookup.get(o1).compareTo(lookup.get(o2));
            }
        };
    }

    public static void main(String[] args) {
        Map<String, Integer> mm = new HashMap<>();
        mm.put("Andrew", 10);
        mm.put("John", 5);
        mm.put("Don", 9);
        mm.put("Rolex", 30);
        mm.put("Jack", 10);
        mm.put("Dan", 9);

        Comparator<String> comparator = reverseComparator(keyedComparator(mm));
        List<String> keys = Arrays.asList(mm.keySet().toArray(new String[mm.size()]));
        //Collections.sort(keys); // optional, if you want the names to be alphabetical
        Collections.sort(keys, comparator);

        int rank = 1, count = 0;
        Integer lastVal = null;
        for (String key : keys) {
            if (mm.get(key).equals(lastVal)) {
                count++;
            } else {
                rank += count;
                count = 1;
            }
            lastVal = mm.get(key);
            System.out.println(key + ", " + mm.get(key) + ", " + rank);
        }
    }
}

In general things like SortedSet make more sense when you need to keep the data itself sorted. When you just need to process something in a sorted manner one time they're usually more trouble than they're worth. (Also: is there any reason why you're using a TreeMap? TreeMaps sort their keys, but not by value, so in this case you're not taking advantage of that sorting. Using a HashMap is more common in that case.)

于 2013-06-25T00:34:28.860 回答
0

您对迭代器做了很多工作,调用 toString(),然后拆分结果。你的 Comparator 也是额外的工作。两边都使用 Map - 您可以更直接地使用 keys() 和 values(),并让 Java 为您进行排序。您上面的大部分代码都可以替换为:(为清楚起见,我将您的名字“mm”更改为“originalMap”)

Map<Integer, String> inverseMap = new TreeMap<Integer, String>();
for (Map.Entry<String, Integer> entry : originalMap.entrySet()) {
  inverseMap.put(entry.getValue(), entry.getKey());
}

现在,遍历 inverseMap 以打印结果。请注意,如果在 originalMap 中确实存在两次计数,则只会打印一个,这就是您想要的。但是哪一个被打印出来作为读者的练习:-)。您可能想要更具体地说明这一点。

编辑添加:如果您确实想打印出重复的分数,这不是您想要的。我阅读的原始帖子说如果它们相同则跳过,但在编辑后我没有看到,所以我不确定这是否是 OP 想要的。

于 2013-06-25T00:36:05.523 回答
0

首先,你为什么要捕获那个 IndexOutOfBoundsException 并且什么都不做?如果你运行它,你会抛出异常(我相信你已经知道了),问题出在最后一个“for”循环内的算法中。我不应该给你解决方案,但是......至少你做了一些努力让它运行,所以这是一个更不工作的版本:

import java.util.*;

public class SortArray {

    static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>>entriesSortedByValues(Map<K,V> map) {
    SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
            new Comparator<Map.Entry<K,V>>() {
                @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                    int res = e1.getValue().compareTo(e2.getValue());
                    return res != 0 ? res : 1;
                    //return e1.getValue().compareTo(e2.getValue());
                }
            });
    sortedEntries.addAll(map.entrySet());
    return sortedEntries;
    }

    public void test(){
    Map mm = new TreeMap();
    mm.put("Andrew", 11);
    mm.put("Mbata", 21);
    mm.put("Chinedu", 14);
    mm.put("Bol", 14);
    mm.put("Don", 51);
    mm.put("Rolex", 16);
    mm.put("Son", 41);
    SortedSet newMap =  entriesSortedByValues(mm);
    Iterator iter = newMap.iterator();
    int x = newMap.size();
    List names = new ArrayList();
    List scores = new ArrayList();
    while(iter.hasNext()){
        String details = iter.next().toString();
        StringTokenizer st = new StringTokenizer(details, "=");
        String name = st.nextToken();
        names.add(name);
        String score = st.nextToken();
        scores.add(score);
        //System.out.println(name + " Score:" +score + " Position:" + x);
        x--;
    }
    Collections.reverse(names);
    Collections.reverse(scores);
    int pos;
    int posBis = 0;
    String lastScore = "";

    for(int i = 0; i<names.size(); i++){
        System.out.print("Name: "+ names.get(i)+"\t");
        System.out.print("Score: "+ scores.get(i)+"\t");
        if(i == 0 || !lastScore.equals(scores.get(i))) {
            pos = i + 1;
            posBis = pos;
        } else {
            pos = posBis;
        }
        System.out.println("Position: "+ String.valueOf(pos));
        lastScore = (String)scores.get(i);
    }
    }

    public SortArray(){
    test();
    }

    public static void main(String [] args){
    new SortArray();
    }

}
于 2013-06-25T00:22:42.133 回答