I need to sort a couple of arraylist
based on another array but don't really know how to go about it.I have the list distance and i sort it using collections. that works perfectly but i want to sort my other list based on the sorted list. This is what i have done so far
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;
}
Comparable
interface for that class. For example:
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);
}
}
you could create a new ComparatorClass that uses your distance list
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.