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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With