简体   繁体   English

Java linq等效项,用于获取具有最高价值的列表中的属性

[英]Java linq equivalent for getting property in list with highest value

Im having a list of results, ArrayList<PlacedObject> result : 我有一个结果列表, ArrayList<PlacedObject> result

for(PlacedObject po : result){

     float[] results = new float[3];

     Location.distanceBetween(lastlocation.getLatitude()
     ,lastlocation.getLongitude()
     ,Double.parseDouble(po.lat)
     ,Double.parseDouble(po.lng) ,
     results);

     po.distance = results[0];
}

After the po.distance is set, i would like to sort my list by the distance property. 设置po.distance之后,我想按distance属性对列表进行排序。 In c# i would use linq, but is there any similar solution in java? 在C#中,我将使用linq,但是在Java中是否有任何类似的解决方案?

Thanks 谢谢


Current solution: 当前解决方案:

Collections.sort(result, new Comparator<PlacedObject>(){
public int  compare(PlacedObject s1, PlacedObject s2) {
    return (int) (s1.distance - s2.distance);
}
});

This is accomplished with the implementation of a Comparator<T> class: 这是通过Comparator<T>类的实现来完成的:

A comparison function, which imposes a total ordering on some collection of objects. 比较功能,对某些对象集合施加总体排序。 Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. 可以将比较器传递给排序方法(例如Collections.sort或Arrays.sort),以精确控制排序顺序。

It could be applied to your list with Collections.sort(list, comparator) . 它可以通过Collections.sort(list,比较器)应用于您的列表。 Basically you implement your own Comparator and pass it to the method. 基本上,您实现自己的Comparator并将其传递给该方法。

An implementation could for instance use an anonymous inner class: 例如,实现可以使用匿名内部类:

Collections.sort(list, new Comparator<PlacedObject>() {

    @Override
    public int compare(PlacedObject po1, PlacedObject po2) {
        return Double.valueOf(po1.distance).compareTo(po2.distance);
    }
});

If you are only intersted in the maximum, as your headline indicates, there is also Collections.max which is applied in the identical way. 如标题所示,如果您只对最大兴趣感兴趣,那么还有Collections.max可以以相同的方式应用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM