Reputation: 1540
Let's say I have
arrayList<String> fruits
that contains
{"banana", "apple", "grape", "banana", "banana", "grape"}
I know how to sort these alphabetically by using a comparator (below) :
Collections.sort(fruits, new Comparator<Fruit>() {
public int compare(Fruit o1, Fruit o2) {
return o1.getName().compareTo(o2.getName());
}
});
However that would give me {"apple", "banana", "banana", "banana", "grape", "grape"}. How would I change this so I get all the bananas listed first, then apples, then grapes? Thanks!
Upvotes: 1
Views: 169
Reputation: 218
You may first create your custom comparator like that :
public static class CustomFruitComparator implements Comparator<String> {
Map<String, Integer> fruitsOrder;
public CustomFruitComparator(Map<String, Integer> fruitsOrder) {
this.fruitsOrder = fruitsOrder;
}
@Override
public int compare(String o1, String o2) {
if (fruitsOrder.get(o1) > fruitsOrder.get(o2))
return 1;
else if (fruitsOrder.get(o1) < fruitsOrder.get(o2))
return -1;
return 0;
}
}
And then you can use it to sort your collection. In your case, you can do like that :
List<String> fruits = Arrays.asList(new String[]{"banana", "apple", "grape", "banana", "banana", "grape"});
Map<String, Integer> fruitsOrder = new HashMap<>();
fruitsOrder.put("banana", 1);
fruitsOrder.put("apple", 2);
fruitsOrder.put("grape", 3);
Collections.sort(fruits, new CustomFruitComparator(fruitsOrder));
Upvotes: 0
Reputation: 4959
This might help get you started:
List<String> fruitsOrder = Arrays.asList(new String[]{"banana","apple","grape"});
Comparator<String> c = Comparator.comparingInt(str -> fruitsOrder.indexOf(str));
You could refine it further, by normalizing the case, and/or by using Comparator.thenComparing, to have a consistent order for fruits not in the list.
Upvotes: 3