Sort an (Array)List with a specific order
here is an other option :
Map<Integer, String> tree = new TreeMap<Integer, String>();
List<String> listOrdre = Arrays.asList("white", "blue", "yellow", "orange", "black", "brown");
List<String> myList = Arrays.asList("orange", "white", "brown", "yellow", "black");
for (String code : myList) {
tree.put(listOrdre.indexOf(code), code);
}
System.out.println(tree.values()); // -> [white, yellow, orange, black, brown]
Yes you can create a Comparator for creating your sort strategy, or define natural-order of your class implementing Comparable
As a side note :
It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y))
Example using Comparator:
class MyClass {
private Color color;
private String someOtherProperty;
public static final Comparator<MyClass> COLOR_COMPARATOR = new MyComparator();
//getter and setter
static class MyComparator implements Comparator<MyClass>{
@Override
public int compare(MyClass o1, MyClass o2) {
// here you do your business logic, when you say where a color is greater than other
}
}
}
And in client code.
Example:
List<MyClass> list = new ArrayList<>();
//fill array with values
Collections.sort(list, MyClass.COLOR_COMPARATOR );
Read more : Collections#sort(..)
If you want to define natural-ordering of your class just define
public class MyClass implements Comparable<MyClass>{
@Override
public int compareTo(MyClass o) {
// do business logic here
}
}
And in client code:
Collections.sort(myList); // where myList is List<MyClass>