简体   繁体   中英

Sort List by Map, using key and after value

I need to sort List by Map, using key of Map. Firstly look at code, afterwards listen to me. I would like to sort List by Key, and after by Value. The result after all should be the following(return only value in List):

/*  The result(List): 
    str3
    str1
    str2
    str4 */

--

List<String> list = ArrayList<>();
list.add("str1");
list.add("str1");
list.add("str3");
list.add("str4"); .......
Map<String, Integer> counts = new HashMap<>();
for (String item:list) {
    Integer count = counts.get(item);
    if (count == null) {
        count = 1;
    } else {
        count = count + 1;
    }
    counts.put(item, count);
}

for (Entry<String, Integer> entry : counts.entrySet()) {
    System.out.println(entry.getValue() + " " + entry.getKey());
}

--

 /*  The result: 
        2 str1
        3 str2
        1 str3
        3 str4 */

Make a custom comparator:

Collections.sort(list, new Comparator<String>() {
    @Override
    public int compare(String left, String right) {
        return Integer.compare(counts.get(left), counts.get(right));
    }
});

Note that you need to make counts final for this to work.


Running this on your example:

public class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("str1");
        list.add("str2");
        list.add("str3");
        list.add("str4");
        final Map<String, Integer> counts = new HashMap<>();
        counts.put("str1", 2);
        counts.put("str2", 3);
        counts.put("str3", 1);
        counts.put("str4", 3);

        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String left, String right) {
                return Integer.compare(counts.get(left), counts.get(right));
            }
        });

        System.out.println(list);
    }
}

Yields:

[str3, str1, str2, str4]

When you want to read the Mapentries sorted by key, you could use a Treemap . Buy maybe you can rephrase the question, it's not very clear what the result should be.

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