2013-04-15 57 views
0

我需要根据另一个阵列对arraylist进行排序,但不知道如何去处理它。我有列表距离,并使用集合对它进行排序。这完美的作品,但我想排序我的另一个列表基于排序列表。这是我迄今为止基于阵列列表排序arraylist a,b,c

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