The best way to prioritize specific lines when sorting a map

I would like to sort the map with the lines, so some lines take precedence, and the rest are ordered as usual.

Like this:

"Dan",   "value"  //priority 1
"Eric",  "value"  //priority 2
"Ann",   "value"  //priority 3
"Bella", "value"  //no priority
"Chris", "value"  //no priority

As in this matter.

I am using TreeMap and my current comparison method is as follows:

public int compare(String o1, String o2) {
    if (o1.equals(o2)) return 0;
    if (o1.equals("Dan")) return -1;
    if (o2.equals("Dan")) return 1;
    if (o1.equals("Eric")) return -1;
    if (o2.equals("Eric")) return 1;
    if (o1.equals("Ann")) return -1;
    if (o2.equals("Ann")) return 1;
    else return o1.compareTo(o2);
}

As you can see, this gets rather cumbersome with higher priority lines.

Is there a better way to do this?


Solution (thanks for the idea): To save priorities, use the second card:

TreeMap<String, Integer> prio = new TreeMap<>();
prio.put("Dan", 1);
prio.put("Eric", 2);
prio.put("Ann", 3);

comparator = new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        if (prio.containsKey(o1)) {
            if (prio.containsKey(o2)) {
                return prio.get(o1).compareTo(prio.get(o2));
            } else return -1;
        } else if (prio.containsKey(o2)) {
            return 1;
        } else return o1.compareTo(o2);
    }
};
+4
source share
1 answer

Use the second card:

Map<String,Integer> priowhere the value is the priority for each row.

prio.get(o1).compareTo(prio.get(o2)) 1 0, compareTo().

, prio map, .


(1) , prio, - .

+3

Source: https://habr.com/ru/post/1569875/


All Articles