java-web - java map排序
PHP中文网
PHP中文网 2017-04-17 12:00:25
0
2
823

需求是这样的:

现在有一个list,里面n个map,每个map都有m大小的key-value,且每个map的key的顺序都是一样的,比如说map1的第x个key是y,那么mapn的第x个key也是y。

现在要对list中的每个map进行排序,要按n个map中的相同的key的value值的和的顺序排序。

举例:比如3个map,都有key1,key2,如果
map1.get(key2) + map2.get(key2) + map3.get(key2) > map1.get(key1) + map2.get(key1) + map3.get(key1),
那么就要将这三个map中的key的顺序按照key2,key1的顺序排列,原先每个map中key的顺序是key1,key2。

怎么来实现呢

PHP中文网
PHP中文网

认证0级讲师

reply all(2)
小葫芦

1. First calculate the sorting of the sum of all keys
2. Traverse the original list, according to the order corresponding to the key, and then put it into a list

List<String> sortedKeys = ...; // 第一步算的结果
List<Map<String, Integer>> originList = ...; // 原始数据集合
List<Map<String, Integer>> resultList = new ArrayList<Map<String, Integer>>();

for(Map<String,Integer> originMap : originList) {
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for(String sortedKey : sortedKeys) {
        sortedMap.put(sortedKey, originMap.get(sortedKey));
    }
    resultList.put(sortedMap);
}
黄舟

Ordered Map can be achieved with TreeMap, so I use java.util.TreeMap in the example.

Generally SortedMap can use a Comparator as a construction parameter, then you can write a Comparator yourself to implement sorting. The following is an example

import java.util.*;

public class Test {
    private SortedMap<String, Integer> first;
    private SortedMap<String, Integer> second;
    private SortedMap<String, Integer> third;
    private SortedMap<String, String> main;

    public Test() {
        first = new TreeMap<String, Integer>();
        second = new TreeMap<String, Integer>();
        third = new TreeMap<String, Integer>();
        main = new TreeMap<String, String>(new Comparator<String>() {
            public int compare(String k1, String k2) {
                Integer v1 = first.get(k1) + second.get(k1) + third.get(k1);
                Integer v2 = first.get(k2) + second.get(k2) + third.get(k2);
                return v2 - v1;
            }
        });
    }

    public void put(String key, String value, Integer v1, Integer v2, Integer v3) {
        first.put(key, v1);
        second.put(key, v2);
        third.put(key, v3);
        main.put(key, value);
    }

    public SortedMap<String, String> getMain() {
        return main;
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.put("a", "aaaaaaaa", 1, 2, 3);
        test.put("b", "bbbbbbbb", 10, 20, 30);
        test.put("c", "cccccccc", 5, 15, 20);
        test.put("d", "dddddddd", 100, 1, 3);

        for (Map.Entry<String, String> entry : test.getMain().entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!