6

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?

1
  • You can override equals and hashcode methods of Object class. Or you can write a Comparator to sort your list with minimum distance on top so you can retrieve it as first element in your list. Commented Apr 17, 2015 at 4:29

6 Answers 6

7

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);
Sign up to request clarification or add additional context in comments.

Comments

5

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);
    }               
}

Comments

1

Use a Priority Queue with a custom Comparator. (Use poll/peek for the minimum value)

public class MyComparator implements Comparator<LocationDistance>
{
  @Override
  public int compare(LocationDistance ld1, LocationDistance ld2)
  {
    return  Double.compare(ld1.distances, ld2.distances);
   }
}
......
......
PriorityQueue collection = new PriorityQueue<LocationDistance>(5, new MyComparator());

Comments

0

@David Limkys is right, that would be a solution in Java 8, for java 6 & 7 the follwing would do.

public class MainCLass {

    /**
     * 
     */
    public MainCLass() {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {

        LocationDistances[] arr = new LocationDistances[] {
                new LocationDistances("abc", 23.234556),
                new LocationDistances("xyz", 3.3444566), };

        ArrayList<LocationDistances> locsDis = new ArrayList(Arrays.asList(arr));

        Collections.sort(locsDis, new Comparator<LocationDistances>() {
            public int compare(LocationDistances o1, LocationDistances o2) {
                return (int)( o1.distances - o2.distances);
            }
        });

    }

}

class LocationDistances {
    String locs;
    double distances;

    /**
     * @param locs
     * @param distances
     */
    public LocationDistances(String locs, double distances) {
        super();
        this.locs = locs;
        this.distances = distances;
    }

    @Override
    public String toString() {
        return String.format("LocationDistances [locs=%s, distances=%s]", locs,
                distances);
    }

}

2 Comments

return (int)( o1.distances - o2.distances); does not work. You could end up rounding the difference to zero when the two original doubles were not equal.
true, alternatively, we could compare them and return 0,1,-1 but i guess i was lazy :)
0

You could implement Comparable on LocationDistances and sort the ArrayList using the comparator for the distance in ascending order.

public class LocationDistances implements Comparable {
    String locs;
    double distances;

    @Override
    public int compareTo(LocationDistances anotherLocation) {
        double otherLocDistances = ((LocationDistances)anotherLocation).getDistances();

        /* ascending order */
        return this.distances - otherLocDistance;

        /* descending order */
        //return otherLocDistance - this.distances;
    }
}

And then call:

ArrayList<LocationDistances> locsDis = new ArrayList(Arrays.asList(
    new LocationDistances("abc",23.234556),
    new LocationDistances("xyz",3.3444566),
    . . . 
    . . .
    . . .

));
Collections.sort(locsDis);

Comments

0

This is what your are looking for:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;


public class Run {
    public static void main(String[]args){
        ArrayList<LocationDistances> locsDis = new ArrayList(Arrays.asList(
                new LocationDistances("abc",23.234556),
                new LocationDistances("xyz",3.3444566)));

        ArrayList<Double> distances = new ArrayList<Double>();
        for (LocationDistances locationDistances : locsDis) {
            distances.add(locationDistances.getDistances());
        }
        double minimum = Collections.min(distances);
        System.out.println(minimum);
    }
}

class LocationDistances  {

    public LocationDistances(String locs, double distances) {
        this.locs = locs;
        this.distances = distances;
    }
    String locs;
    double distances;
    public String getLocs() {
        return locs;
    }
    public void setLocs(String locs) {
        this.locs = locs;
    }
    public double getDistances() {
        return distances;
    }
    public void setDistances(double distances) {
        this.distances = distances;
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.