繁体   English   中英

根据列表值对地图进行排序

[英]Sorting map based on list values

我有下面的地图:

Map<String, String> map1 = new HashMap<String, String>();

内容是:

ID_1 -> ID_2
------------
100 -> 10
200 -> 20
300 -> 30

基于ID_2的值,我必须查询一个oracle表并获取与每个条目相对应的代码值:

ID_1 -> ID_2 -> code
--------------------
100 -> 10 -> 8
200 -> 20 -> 2
300 -> 30 -> 9

然后我将不得不按代码值升序对map1进行排序,即结果应为:

200 -> 20
100 -> 10
300 -> 30

我曾考虑过创建一个中间映射,其中<ID_1, List<ID_2,code>><K,V> ,然后使用代码值进行排序,然后得到最终输出。

有没有更短的方法,例如不使用中介地图?

您可以在下面尝试以下代码:我使用int[]数组而不是List

public class Test {

    public static void main(String[] args) throws Exception {
        Map<String, int[]> map = new HashMap<>();
        map.put("100", new int[]{10, 8});
        map.put("200", new int[]{20, 2});
        map.put("300", new int[]{30, 9});

        Map<String, int[]> sortByValue = sortByValue(map);
        for (Map.Entry<String, int[]> entry : sortByValue.entrySet()) {
            System.out.println(entry.getKey() +" -> "+ entry.getValue()[0]);
        }

    }

    private static Map<String, int[]> sortByValue( Map<String, int[]> map ) {
        List<Map.Entry<String, int[]>> list = new LinkedList<>(map.entrySet());
        Collections.sort(list, (o1, o2) -> Integer.compare(o1.getValue()[1], o2.getValue()[1]));
        Map<String, int[]> result = new LinkedHashMap<>();
        for (Map.Entry<String, int[]> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }
}

结果是:

200 -> 20
100 -> 10
300 -> 30

基于map1,您可以构建新地图:

 Map<String, Pair<String, String> map2

其中键是来自oracle db的ID。

需要订购时,可以使用TreeMap和method

Map.Entry<K,V> firstEntry();

我将向您表达以下逻辑:

  1. 获取地图中的所有条目
  2. 影响每个人的分数(通过数据库调用)
  3. 根据步骤2在最终地图中订购条目

重要的是要注意,很少有地图具有排序约束。 我想到的基本实现是LinkedHashMap。 此外,“对现有地图进行重新排序”似乎是一个奇怪的想法, Map 接口中的任何方法均未对此进行支持。 简而言之,说您需要返回一个具有排序约束的Map似乎是一个不好的/不完整的想法-但这当然是可行的。

我也反对使用TreeMap ,它是由Comparator排序的Map,因为我没有看到您的排序值唯一的约束。 另外,您的订购取决于地图的值,而不是键。 这样的比较器根本不是简单的。

简而言之,我要做的是

    LinkedHashMap<String, String> sorted = map.entrySet().stream()
        // This is your DB call
        .sorted(Comparator.comparing(entry -> getDBValue(entry)))
        // Now we have an ordered stream of key/value entries from the original map
        .collect(
            // We flush back to a Map
            Collectors.toMap(
                    // Keeping the original keys as is
                    Map.Entry::getKey, 
                    // Keeping the original values as is
                    Map.Entry::getValue, 
                    // This merge step should never be called, as keys are unique. Maybe you could assert that and fail if this is called
                    (v1, v2) -> v1,
                    // This is where you instanciate the Map that respects ordering of keys. Here, LinkedHashMap is iterable in the order of insertion, which is what we want.
                    LinkedHashMap::new
                  )
    );

使用Java流,您可以在不使用任何其他集合的情况下实现此目的,这是一个实现。

为了保持秩序,在收集器中使用了LinkedHashMap

为简单起见,我又制作了一张地图来保存db值[您需要更改此值才能从DB中获取]

    Map<String, String> map1 = new HashMap<String, String>();
    map1.put("100", "10");
    map1.put("200", "20");
    map1.put("300", "30");

    Map<String, String> dbmap = new HashMap<String, String>();
    dbmap.put("10", "8");
    dbmap.put("20", "2");
    dbmap.put("30", "9");

    Comparator<String> comp = (k1, k2) -> dbmap.get(map1.get(k1)).compareTo(dbmap.get(map1.get(k2)));

    Map<String, String> queryMap = map1.keySet().stream().sorted(comp)
            .collect(toMap((String key) -> key, value -> (String) map1.get(value), (u, v) -> {
                throw new IllegalStateException(String.format("Duplicate key %s", u));
            }, LinkedHashMap::new));

    System.out.println(queryMap);

乌普特

{200=20, 100=10, 300=30}

暂无
暂无

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

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