How to sort two arrays in relation to each other.

I have 2 arrays:

private String[] placeName;
private Double[] miles;

The data in them is as follows:

placeName = {"home", "away", "here"};
miles = {111, 11, 3};

The position of the values ​​corresponds to each other. those. home = 111 and away = 11

I need to sort these arrays together, so I do not lose how they are matched with the number - the lowest to the highest. What is the best way to do this? Do arrays need to be combined first?

+4
source share
3 answers

, , , , . . , , .

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

, , MyDistance Comparable, Comparator<MyDistance> :

public class DistanceComparator extends Comparator<MyDistance> {
    @Override
    public int compare(MyDistance dist1, MyDistance dist2) {
        return dist1.getMilage().compareTo(dist2.getMilage());
    }
}

:

List<MyDistance> distanceList = getDistanceListSomehow();
Collections.sort(distanceList, new DistanceComparator());

, . Java, , . , , ArrayList , .

+4

- TreeMap. , .

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

. , . "", 11 , , "", . , MultiMap ...

+2

, TreeMap

SortedMap<Double,String> map = new TreeMap<>();
map.put(111,"home");
map.put(11,"away");
map.put(3,"here");

0
source

Source: https://habr.com/ru/post/1542954/


All Articles