Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort the List<Size> in Android

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.

like image 996
jjLin Avatar asked Nov 30 '25 16:11

jjLin


2 Answers

Use a custom Comparator.

A Comparator is used to compare two objects to determine their ordering with respect to each other. On a given Collection, a Comparator can be used to obtain a sorted Collection which 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;
  }
});
like image 58
obataku Avatar answered Dec 03 '25 05:12

obataku


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());
    }
}
like image 43
Bharat Sinha Avatar answered Dec 03 '25 05:12

Bharat Sinha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!