Comparator with double type

前端 未结 10 1536
盖世英雄少女心
盖世英雄少女心 2020-11-28 11:50

I have written the following code:

public class NewClass2 implements Comparator
{
    public int compare(Point p1, Point p2)
    {
        retur         


        
相关标签:
10条回答
  • 2020-11-28 12:18

    Use Double.compare(/**double value 1*/, /**double value 2*/); with a new Comparator for your model class double value.

    public static List<MyModel> sortByDouble(List<MyModel> modelList) {
            Collections.sort(modelList, new Comparator<MyModel>() {
                @Override
                public int compare(MyModels1, MyModels2) {
                    double s1Distance = Double.parseDouble(!TextUtils.isEmpty(s1.distance) ? s1.distance : "0");
                    double s2Distance = Double.parseDouble(!TextUtils.isEmpty(s2.distance) ? s2.distance : "0");
                    return Double.compare(s1Distance, s2Distance);
                }
            });
            return modelList;
        }
    
    0 讨论(0)
  • 2020-11-28 12:19

    Well, you could multiply those double values by an appropriate factor before converting into integer, for eg. in your case since its only one decimal place so 10 would be a good factor;

    return (int)(p1.getY()*10 - p2.getY()*10);
    
    0 讨论(0)
  • 2020-11-28 12:30

    I just want to expand on Peter Lawrey answer on JDK 8, if you do it like this:

    public class NewClass2 implements Comparator<Point> {
        public int compare(Point p1, Point p2) {
            return Double.compare(p1.getY(), p2.gety());
        }    
    }
    

    You could define this comparator using a lambda expression pretty easily

    (Point p1,Point p2) -> Double.compare(p1.getY(), p2.gety())  
    

    Better yet, you could use a member reference like this:

    Double::compare
    
    0 讨论(0)
  • 2020-11-28 12:30
    Double min  = Arrays.stream(myArray).min(Double::compare).get();
    
    0 讨论(0)
提交回复
热议问题