I have 2 arrays:
private String[] placeName;
private Double[] miles;
The data in them look like this:
placeName = {"home", "away", "here"};
miles = {111, 11, 3};
The position of the values match to each other. ie home = 111 and away = 11
I need to sort these arrays together so I don't lose how they are matched by the the number- lowest to highest. What is the best way to accomplish this? Do I need to combine the arrays first?
Since the two values are so tightly coupled together I would actually write a custom class to contain the information and then sort those classes instead of playing around with raw arrays. Doing so would leave you open to many possible bugs down the line.
This allows for much better control, data encapsulation and future expansion of what methods or data your class may contain.
public class MyDistance implements Comparable<MyDistance> {
private String placename;
private double mileage;
public MyDistance(String placename, double milage) {
this.placename = placename;
this.milage = milage;
}
public String getPlacename() {
return this.placename;
}
public double getMilage() {
return this.milage;
}
@Override
public int compareTo(MyDistance anotherDistance)
{
return milage.compareTo(anotherDistance.getMilage());
}
}
If you want more flexibility in your sort then instead of having your MyDistance class implement Comparable you can write a custom Comparator<MyDistance>
class:
public class DistanceComparator extends Comparator<MyDistance> {
@Override
public int compare(MyDistance dist1, MyDistance dist2) {
return dist1.getMilage().compareTo(dist2.getMilage());
}
}
You can use this Comparator to sort using Collections:
List<MyDistance> distanceList = getDistanceListSomehow();
Collections.sort(distanceList, new DistanceComparator());
You are not restricted to a List, I just used it for explanatory purposes. You should look at the full range of Java Collections types to best choose one that suits your purposes. As a suggestion though, the ArrayList type is easy to use and retains order like you would want.
One way is to create a TreeMap. Assuming you are sorting by miles.
TreeMap tm = new TreeMap<Double, String>();
for (int i=0; i<miles.length; i++) {
tm.put(miles[i], placeName[i]);
}
// tm is already sorted - iterate over it...
NOTE: IF you have places with the same exact distance in miles this will not work. e.g. if you had a "work" that was 11 miles, just like "away", this won't work. You'd probably want some form of MultiMap for that...
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