简体   繁体   中英

How to sort a map of type Map<String, List<String>> in Java

Issue

I'm trying to sort a map Map> which the map key set contain the order 1 2 3 4 ext ...

Code

The file which I'm retrieving data filter.properties 1=gwtCacheControlFilter:com.palmyra.arch.presentation.port.server.GWTCacheControlFilter:true:/*:null:presentation

    public Map<String, List<String>> initiateMapOfFilters() throws IOException {

        Map<String, List<String>> filterMap = new HashMap<>();

        Properties properties = new Properties();
        properties.load(FilterFileStream);

        for (Entry<Object, Object> filterFromFile : properties.entrySet()) {

            String filterValue = filterFromFile.getValue().toString();
            String[] split = filterValue.split(":");

            ArrayList<String> list = new ArrayList<>();
            for (String s : split) {
                list.add(s);
            }


            //-------sort the list with order
            filterMap.put(split[filterNameIndex], list);        

        }
//      Map<String, String> treeMap = new TreeMap<String, String>((Comparator<? super String>) filterMap); comment
        return filterMap;
    }

What I've tried

I want to return a map ordered by the key I tried:

Map<String, String> treeMap = new TreeMap<String, String>((Comparator<? super String>) filterMap);

Thank you for any suggestion.

You have to use a comparator to make it work! Like this :

Map<Integer,String> unsortedMap = new Hashmap<Integer,String>();
Map<Integer,String> treeMap = new TreeMap<Integer,String>(
    new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);//sort in descending order
        }
        });

Consider the below code. With java 8 you can use the Comparator.comparing method and get it done quite quickly.

        TreeMap<String, List<String>> treeMap = new TreeMap<>(Comparator.comparing(t -> Integer.valueOf(t)));

        treeMap.put("5", Arrays.asList(new String[] {"data1", "data2", "data3"}));
        treeMap.put("3", Arrays.asList(new String[] {"data4", "data5", "data6"}));
        treeMap.put("1", Arrays.asList(new String[] {"data7", "data8", "data9"}));
        treeMap.put("4", Arrays.asList(new String[] {"data10", "data11", "data12"}));

        treeMap.
                forEach((k,v) -> System.out.println(k + "=="+v));

Output is sorted on basis of keys:

1==[data7, data8, data9]
3==[data4, data5, data6]
4==[data10, data11, data12]
5==[data1, data2, data3]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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