I have a list of object and need to sort it based on specific order. Something like below code:
preOrderedList = {"bmw","audi","benz"};
The list which comes from UI is carList {"audi","benz","bmw"}
.
Problem here is user will be able to add a new row from application. Suppose if user adds a new row of "audi", then the carList will be like
{"audi","benz","bmw","audi"}
. In this case the list should be sorted like {"bmw","audi","audi","benz"}.
I have tried below code. It works only for without adding a new row, means {"audi","benz","bmw"}
.
That too while it gets sorts only the name("bmw","audi","benz") position is getting changed. I have one more field in Car class which is quantity. quantity will be in same position. This position should also get changed along with name.
final List<String> preOrderedList = Arrays.asList("bmw","audi","benz");
Collections.sort(carList, new Comparator<Car>() {
public int compare(Car l1, Car l2) {
if (preOrderedList.contains(l1.getName().trim()) && preOrderedList.contains(l2.getName().trim())) {
return preOrderedList.indexOf(l1.getName().trim()) - preOrderedList.indexOf(l2.getName().trim());
}
if (preOrderedList.contains(l1.getName().trim())) {
return -1;
}
if (preOrderedList.contains(l2.getName().trim())) {
return 1;
}
return l1.getName().trim().toString().compareTo(l2.getName().trim().toString());
}
});
I Expect the output as {"bmw","audi","audi","benz"}
but my actual output is {"bmw","audi","benz","audi"}.
This can be elegantly solved with guava's Ordering.explicit
:
Collections.sort(carList, Ordering.explicit(preOrderedList).onResultOf(new Function<Car, String>() {
@Override
public String apply(Car car) {
return car.getName();
}
}));
The last version of Guava thas supports Java 6 is Guava 20.0:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>