对TreeMap java中的值进行排序

时间:2017-09-14 22:21:15

标签: java

编辑:解决了。我需要将定义的顺序切换为Integer,Action

我创建了一对一的TreeMap,其中键是枚举,值是整数。我想循环从最小到最大的值,我遇到了一些麻烦。

创建地图的功能

public TreeMap<Action,Integer> mapMoves(int position, ArrayList<Action> directions){
    TreeMap<Action,Integer> map = new TreeMap<>();
    for(Action a : directions){
        switch(a){
            case UP:
                map.put(a,board.get(position-3));
                break;
            case DOWN:
                map.put(a,board.get(position+3));
                break;
            case LEFT:
                map.put(a,board.get(position-1));
                break;
            case RIGHT:
                map.put(a,board.get(position+1));
                break;
        }
    }
    return map;
}

当我运行以下for循环时,它不会按升序打印值。

TreeMap<Action, Integer> map = current.hashMoves(emptyIndex, possibleMoves);
for (Map.Entry<Action, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
 }

1 个答案:

答案 0 :(得分:1)

我猜动作是枚举,Enum已经实现了Comparable。

它使用枚举常量定义的顺序,但遗憾的是你不能覆盖compareTo方法来实现字典排序,因为它被定义为final。

但您可以将自定义Comparator传递给TreeMap。

将地图切换为<Integer,Action>或使用

按值排序
static <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
    Comparator<K> valueComparator = (k1, k2) -> {
        int compare = map.get(k2).compareTo(map.get(k1));
        if (compare == 0) return 1;
        else return compare;
    };
    Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);
    return sortedByValues;
}
static TreeMap<Action,Integer> mapMoves() {
    List<Action> directions = new ArrayList<>();
    directions.add(Action.DOWN);
    directions.add(Action.UP);
    directions.add(Action.UP);
    directions.add(Action.UP);
    directions.add(Action.LEFT);
    directions.add(Action.LEFT);
    directions.add(Action.RIGHT);
    directions.add(Action.RIGHT);
    TreeMap<Action,Integer> map = new TreeMap<>();
    for(Action a : directions){
        switch (a){
            case UP:
                map.put(a, 10);
                break;
            case DOWN:
                map.put(a, 2);
                break;
            case LEFT:
                map.put(a, 30);
                break;
            case RIGHT:
                map.put(a, 4);
                break;
        }
    }
    return map;
}

enum Action {
    UP, DOWN, LEFT, RIGHT
}

    TreeMap<Action, Integer> map = mapMoves();
    map.entrySet().stream().forEach(e -> System.out.println("e = " + e.getKey() + ": " + e.getValue()));
    System.out.println("- - -");
    Map<Action, Integer> sortedMapByValuesDescOrder = sortByValues(map);
    sortedMapByValuesDescOrder.entrySet().stream().forEach(e -> System.out.println("e = " + e.getKey() + ": " + e.getValue()));

输出

e = UP: 10
e = DOWN: 2
e = LEFT: 30
e = RIGHT: 4
- - -
e = LEFT: 30
e = UP: 10
e = RIGHT: 4
e = DOWN: 2