Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Put in specific order to treemap

I have a big list and put it into a treemap.

Then I want to put "ALL" at the very top of the list, but there is "AAA" something that comes before "ALL"

edit: And I want all other inputs to be sorted

List     ->    List
-----          -----
AAA            AAA
BBB            ALL
CCC            BBB
               CCC

I could use arrayList or something else but I was wondering if there is a way to control this situation.

like image 229
sayhaha Avatar asked Dec 15 '22 23:12

sayhaha


2 Answers

One option would be to build a custom comparator that always ranks the word "ALL" before everything else:

TreeMap<String, T> myMap = new TreeMap<String, T>(new Comparator<String>() {
    public int compare(String lhs, String rhs) {
        /* See which of the inputs, if any, are ALL. */
        bool oneAll = lhs.equals("ALL");
        bool twoAll = rhs.equals("ALL");

        /* If both are ALL or neither are ALL, just do a normal comparison. */
        if (oneAll == twoAll) {
            return lhs.compareTo(rhs);
        }
        /* Otherwise, exactly one of them is ALL.  Determine which one it is and
         * react accordingly.
         */
        else if (oneAll) {
            return -1;
        } else {
            return +1;
        }
    }
});

This will sort everything in ascending order, but prioritize "ALL" above everything else.

Hope this helps!

like image 110
templatetypedef Avatar answered Dec 30 '22 11:12

templatetypedef


Don't use TreeMap, basically. If you want to put things in a specific order, just use an ArrayList or a LinkedList instead. TreeMap orders its entries in the order of its keys. You don't want that in this case.

EDIT: If you're just concerned with putting ALL at the top, then a custom comparator is fine. But if you really want to be able to specify the position of each entry in a way which isn't easily determined purely by the keys involved, then I stand by my suggestion that TreeMap is not the way forward.

like image 21
Jon Skeet Avatar answered Dec 30 '22 11:12

Jon Skeet