我需要根据另一个数组对几个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;
}
答案 0 :(得分:2)
Comparable
接口。例如:
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);
}
}
答案 1 :(得分: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);