0

我需要arraylist根据另一个数组对几个进行排序,但真的不知道如何去做。我有列表距离,我使用集合对其进行排序。这工作得很好,但我想根据排序列表对我的其他列表进行排序。这是我到目前为止所做的

private void sortList() {
    List<Float> tempDistance = new ArrayList<Float>();
    List<Float> tempmyLat = new ArrayList<Float>();
    List<Float> tempmyAlt = new ArrayList<Float>();
    List<Float> tempmyLng = new ArrayList<Float>();
    ArrayList<HashMap<String, String>> tempplacesListItems = new ArrayList<HashMap<String, String>>();

    tempDistance = Distance;
    tempmyLat = myLat;
    tempmyLng = myLng;
    tempmyAlt = myAlt;
    tempplacesListItems = placesListItems;

    Collections.sort(tempDistance);

    for (int i = 0; i < Distance.size(); i++) {
        Log.d("sorted distance", "" + tempDistance.get(i));
        for (int k = 0; k < tempDistance.size(); k++) {
            if (Distance.get(i) == tempDistance.get(k)) {
                tempplacesListItems.set(k, placesListItems.get(i));
                tempmyLat.set(k, myLat.get(i));
                tempmyLng.set(k, myLng.get(i));
                tempmyAlt.set(k, myAlt.get(i));
            }
        }
    }

    myLat = tempmyLat;
    myLng = tempmyLng;
    myAlt = tempmyAlt;
    placesListItems = tempplacesListItems;
}
4

2 回答 2

2
  1. 将所有 4 个值放在自定义类中。
  2. 实现Comparable该类的接口。
  3. 根据您的输入列表制作该类的对象列表。
  4. 对对象列表进行排序。

例如:

private void sortList() {
    List<MyTuple> tuples = new ArrayList<>();

    for (int i = 0; i < Distance.size(); i++) {
        tuples.add(new MyTuple(Distance.get(i), myLat.get(i), 
                                myAlt.get(i), myLon.get(i)));
    }

    Collections.sort(tuples);

    // do something with tuples
}

private class MyTuple implements Comparable<MyTuple> {
    private float distance;
    private float latitude;        
    private float longitude;
    private float altitude;

    public MyTuple(float distance, float altitude, 
                   float latitude, float longitude) {
        this.distance = distance;
        this.latitude = latitude;            
        this.longitude = longitude;
        this.altitude = altitude;
    }

    public int compareTo(MyTuple other) {
        return Float.compare(this.distance, other.distance);
    }
}
于 2013-04-15T07:55:38.763 回答
0

您可以创建一个使用您的距离列表的新 ComparatorClass

class DistanceBasedComparator<Float> implements Comparator {
    private List<Float> distances;

    public DistanceBastedComparator(List distances) {
        this.distances = distances;
    }

    public compare(Float f1, Float f2) {
        // implement your comparison here
    }
}
[...]
Comparator comp = new DistanceBaseComparator(tempDistance );

Arrays.sort(tempMyLat, comp);
于 2013-04-15T07:59:45.930 回答