2017-09-14 46 views
1

编辑里面的值:解决。我需要定义的顺序切换为整数,动作排序一个TreeMap的java

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

功能当我运行下面的for循环不按升序排列打印值它创建地图

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; 
} 

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

,因为你的关键是 “行动”,而不是数量 – IddoE

+0

如果我可以这样说,我认为你正在尝试使用一个数据结构来实现它没有为之而作。为了给出一个建议,你可以对'directions'数组进行排序,并使TreeMap指向数组中的位置。这样,您就拥有了两全其美的优势:您可以使用TreeMap快速获取使用键搜索的值,并且只需使用排序的数组即可按顺序打印所有值。 – Discoverer98

+0

好的。直觉上似乎倒退到我,因为密钥通常字符串和值是数字 –

回答

1

我猜Action是Enum,Enum已经实现了Comparable。

它采用枚举常量的定义的顺序,但可悲的是,你不能覆盖的compareTo的方法来实现,因为它被定义为最后的字典序。

但是你可以通过自定义的比较,以树形图。

或者切换地图<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