sorting - Java, sort arraylist by custom alpha order -
let's have
arraylist<string> fruits
that contains
{"banana", "apple", "grape", "banana", "banana", "grape"}
i know how sort these alphabetically using comparator (below) :
collections.sort(fruits, new comparator<fruit>() { public int compare(fruit o1, fruit o2) { return o1.getname().compareto(o2.getname()); } });
however give me {"apple", "banana", "banana", "banana", "grape", "grape"}. how change bananas listed first, apples, grapes? thanks!
this might started:
list<string> fruitsorder = arrays.aslist(new string[]{"banana","apple","grape"}); comparator<string> c = comparator.comparingint(str -> fruitsorder.indexof(str));
you refine further, normalizing case, and/or using comparator.thencomparing, have consistent order fruits not in list.
Comments
Post a Comment