按特定参数对对象列表进行排序

问题描述 投票:0回答:3

我有和具有多个参数的对象的ArrayList。我需要创建一个方法,通过某个参数对列表进行排序。我的班级是:

public class VehicleLoaded {

private int vlrefid;
private int vehicleRefId;
private int load_time;
...

public ELPEVehicleLoaded(){}
}

我需要按加载时间(按升序)对包含此类对象的ArrayList进行排序。这是我的比较器:

public static Comparator<ELPEVehicleLoaded> RouteLoadingTime = new Comparator<ELPEVehicleLoaded>() 
{
    public int compare(ELPEVehicleLoaded vl1, ELPEVehicleLoaded vl2) {

    int vl1_load_time=vl1.getLoadTime();

    int vl2_load_time=vl2.getLoadTime();
    /*For ascending order*/
    return vl1_load_time-vl2_load_time;
}};

因此我创建了一个静态方法来排序:

public static void sortListByLoadTime (ArrayList<VehicleLoaded> VLs){
Collections.sort(VLs, new MyComparator());
}

对不起,如果这个问题再次出现,我一直在寻找,但找不到适合我的答案。非常感谢你提前!

java sorting
3个回答
1
投票
public class HelloWorld {
    public static void main(String[] args) {
        List<MyObj> a = Arrays.asList(new MyObj(5), new MyObj(4),new MyObj(3),new MyObj(2), new MyObj(1));

        Collections.sort(a, Comparator.comparingInt(MyObj::getLoadTime));

        System.out.println(a);
    }
}

class MyObj {
    int loadTime;

    public MyObj(int loadTime) {
        this.loadTime = loadTime;
    }

    public int getLoadTime() {
        return loadTime;
    }

    @Override
    public String toString() {
        return "" + loadTime;
    }
}

这个输出将是:

[1, 2, 3, 4, 5]

所以在你的情况下你需要添加到你的sortListByLoadTime方法是:

Collections.sort(VLs, Comparator.comparingInt(ELPEVehicleLoaded::getLoadTime));

当我们谈论一个ArrayList时,你应该使用它的排序方法而不是Collections :: sort。在我给它的例子中,它将是:

Collections.sort(VLs, Comparator.comparingInt(ELPEVehicleLoaded::getLoadTime)); - > VLs.sort(Comparator.comparingInt(ELPEVehicleLoaded::getLoadTime));


1
投票

您可以尝试Java 8方式:

VLs.stream()
    .sorted((v1,v2)-> {
        if(v1.getLoadTime()<v2.getLoadTime()) {
            return -1;
        }
        if(v1.getLoadTime()>v2.getLoadTime()) {
            return 1;
        }
        return 0;
    }).collect(Collectors.toList());

1
投票

您可以在函数comparator中使用sortListByLoadTime,如下所示:

VLs.sort((o1,o2) -> o1.getLoadTime() - o2.getLoadTime());

或者您可以使用Collections utility,如下所示:

Collections.sort(VLs, ( o1,  o2) -> {
      return o1.getLoadTime() - o2.getLoadTime();
});

lambda expression可以被method reference取代,如下所示:

Collections.sort(VLs, Comparator.comparing(VehicleLoaded::getLoadTime));
© www.soinside.com 2019 - 2024. All rights reserved.