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

I have a class

public class LocationDistances {
    String locs;
    double distances;

}

and an ArrayList composed of LocationDistances objects in another class

ArrayList 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?

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 min=new  ArrayList();

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);
    }
}
Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Select an object based on its minimum attribute value from the list in Java

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录