Reputation: 35213
Im having a list of results, 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. In c# i would use linq, but is there any similar solution in java?
Thanks
Current solution:
Collections.sort(result, new Comparator<PlacedObject>(){
public int compare(PlacedObject s1, PlacedObject s2) {
return (int) (s1.distance - s2.distance);
}
});
Upvotes: 0
Views: 194
Reputation: 29543
This is accomplished with the implementation of a Comparator<T>
class:
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.
It could be applied to your list with Collections.sort(list, comparator). Basically you implement your own Comparator and pass it to the method.
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.
Upvotes: 3