I have a class
public class LocationDistances {
String locs;
double distances;
}
and an ArrayList composed of LocationDistances objects in another class
ArrayList<LocationDistances> locsDis = new ArrayList(Arrays.asList(
new LocatoinDistances("abc",23.234556),
new LocatoinDistances("xyz",3.3444566),
. . .
. . .
. . .
));
How to select LocationDistances.locs from Array list on the basis of minimum value of LocationDistances.distance from the locsDis arrayList?
In order to compute minimum element of ArrayList with Java Collections, we use the Collections. min() method.
contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.
If you are using Java 8 (You should :)) :
locsDis.stream().min((first, second) -> Double.compare(first.distance, second.distance)).get();
Edit: Decided to make this post a bit more comprehensive to help those of us that are still confined to Java < 8
but can use the awesome library guava :)
Java 6 & 7 With guava (Google util library):
Ordering<LocationDistances> ordering = new Ordering<LocationDistances>() {
@Override
public int compare(LocationDistances left, LocationDistances right) {
return Double.compare(left.distance, right.distance);
}
};
return ordering.max(list);
Something like this would work if there are no duplicate distances.
LocationDistances min=null;
for(LocationDistances x:locsDis){
min=(min==null||x.distances<min.distances)?x:min;
}
String minimumDistance=min.locs;
if there are duplicate distances use something like this
ArrayList<LocationDistances> min=new ArrayList<LocationDistances>();
for(LocationDistances x:locsDis){
if(min.size()==0||x.distances==min.get(0).distances)
min.add(x);
else if(x.distances<min.get(0).distances){
min.clear();
min.add(x);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With