I have a List<Size> list1 which is from parameters.getSupportedPreviewSizes()
I would like to sort it in ascending order (width * height).
I have tried Collection.sort, but seems not work.
What is the best way to sort the list? Thanks.
Use a custom Comparator.
A
Comparatoris used to compare two objects to determine their ordering with respect to each other. On a givenCollection, aComparatorcan be used to obtain a sortedCollectionwhich is totally ordered.
final Camera camera = ...;
final List<Camera.Size> sizes = camera.getParameters().getSupportedPreviewSizes();
Collections.sort(sizes, new Comparator<Camera.Size>() {
public int compare(final Camera.Size a, final Camera.Size b) {
return a.width * a.height - b.width * b.height;
}
});
You need to implement a Comparable interface to specify how an object is evaluated against to other and then use Collections.sort() method to sort in the desired order.
class Size implements Comparable<Size>{
Integer width;
Integer height;
public Integer getArea(){
return width*height;
}
@Override
public int compareTo(Size o) {
return getArea().compareTo(o.getArea());
}
}
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