Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select an object on the basis of its minimum attribute value from list in Java

Tags:

java

arraylist

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?

like image 578
Faisal Naseer Avatar asked Apr 17 '15 04:04

Faisal Naseer


People also ask

How do you find the minimum value in an ArrayList?

In order to compute minimum element of ArrayList with Java Collections, we use the Collections. min() method.

How do you check if an item in a list is in another list Java?

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.


Video Answer


2 Answers

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);
like image 130
David Limkys Avatar answered Sep 25 '22 01:09

David Limkys


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);
    }               
}
like image 44
prasadmadanayake Avatar answered Sep 23 '22 01:09

prasadmadanayake