Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort two arrays with respect to eachother.

Tags:

java

arrays

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?

like image 692
BluGeni Avatar asked Jun 02 '14 16:06

BluGeni


2 Answers

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.

like image 117
indivisible Avatar answered Sep 19 '22 18:09

indivisible


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...

like image 30
user949300 Avatar answered Sep 21 '22 18:09

user949300