简体   繁体   English

如何基于另一个数组对数组进行排序

[英]How to sort an Array based off on another array

I'm developing an Android app. 我正在开发一个Android应用程序。 I need to sort an array based off of the sorting of another. 我需要对另一个数组进行排序。 I'm sorting one (distance) based off of lowest to highest, and need for my longitude values to be sorted according to the distance. 我正在从最低到最高排序一个(距离),并且需要根据距离对我的经度值进行排序。 So say if distance 5 had longitude 41.2265 and distance 6 had longitude 41.2187, I would need to sort the distances from lowest to highest, {5,6}, and then sort the longitudes based off of their first pair. 假设如果距离5的经度为41.2265,距离6的经度为41.2187,则我需要从最低到最高的距离{5,6}进行排序,然后根据它们的第一对对经度进行排序。 I have read that you could do this with a 2D array, but I would prefer not to do this. 我读过您可以使用2D阵列执行此操作,但我不希望执行此操作。 I think this also could be done with mapping, but I'm not sure how. 我认为这也可以通过映射完成,但是我不确定如何做。 My code is below: 我的代码如下:

Part of NearestStations.java NearestStations.java的一部分

            ArrayList<String> distancetos = new ArrayList<String>();
            ArrayList<String> longitudeArray = new ArrayList<String>();

            while(iterator.hasNext()){
            for (int i=0; i<144;i++){

            double distance = 0;  

            double lat_end = 0;
            double lon_end = 0;


            try {
                lat_end = Double.parseDouble(iterator.next());
                lon_end = Double.parseDouble(iterator1.next());
                longitudeArray.add(Double.toString(lon_end));
                Log.i("Lon_end", String.valueOf(lon_end));

            } catch (NumberFormatException e) {
                Log.v("Main", "Convert to Double Failed : ");
            }

            Location locationA = new Location("point A");  
            locationA.setLatitude(latitude);  
            locationA.setLongitude(longitude);  

            Location locationB = new Location("point B");  
            locationB.setLatitude(lat_end);  
            locationB.setLongitude(lon_end);  

            distance = locationA.distanceTo(locationB) * 0.000621371192237334;
            Log.i("distancebefore", String.valueOf(distance));

            String dista = Double.toString(distance);


            distancetos.add(dista);
            }
            }


                Collections.sort(distancetos);

                distancea = distancetos.get(0);
                distance1 = distancetos.get(1);

                String Longa = longitudeArray.get(0);
                String Long1 = longitudeArray.get(1);


                Log.i("distanceafter", String.valueOf(distancea));
                Log.i("distance1after", String.valueOf(distance1));


            String[] Stations = getResources().getStringArray(R.array.Stations);
            String[] Longitude = getResources().getStringArray(R.array.Longitude);
            String[] Latitude = getResources().getStringArray(R.array.Latitude);



            Map<String, String> myMap = new HashMap<String, String>();{
            for (int i = 0; i <144; i++) {
                myMap.put(Latitude[i], Stations[i]);
            }
            }

            Map<String, String> myMap1 = new HashMap<String, String>();{
            for (int h = 0; h <144; h++) {
                myMap1.put(Longitude[h], Stations[h]);

            }
            }

            String value = myMap1.get(Longa);
   }
}

Thank you for your help. 谢谢您的帮助。

I believe this is what you're looking for. 我相信这就是您要寻找的。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

public class GenericCachedSorter {
    public static void main(String[] args) {
        List<Double> distances = new ArrayList<>(Arrays.asList(1d, 2d, 3d));

        sort(distances, new ToComparable<Double, Double>() {
            @Override
            public Double toComparable(Double distance) {
                // return the longitude associated with this distance
                return getLongitude(distance);
            }
        });

        for (Double distance : distances)
            System.out.println(distances);
    }

    public interface ToComparable<T, C extends Comparable<? super C>> {
         C toComparable(T t);
    }

    public static <T, C extends Comparable<? super C>> void sort(List<T> list, ToComparable<T, C> function) {
       class Pair implements Comparable<Pair> {
          final T original;
          final C comparable;

          Pair(T original, C comparable) {
             this.original = original;
             this.comparable = comparable;
          }

          @Override
          public int compareTo(Pair other) {
                return
                  comparable == null && other.comparable == null ? 0 :
                  comparable == null ? -1 :
                  other.comparable == null ? 1 :
                  comparable.compareTo(other.comparable);
          }
       }

       List<Pair> pairs = new ArrayList<>(list.size());
       for (T original : list)
          pairs.add(new Pair(original, function.toComparable(original)));

       Collections.sort(pairs);

       ListIterator<T> iter = list.listIterator();
       for (Pair pair : pairs) {
          iter.next();
          iter.set(pair.original);
       }
    }
}

How about making a class for them? 为他们上课怎么样?

public class Coord{
    private int id;
    private double lat;
    private double long;

    public double getDistanceFrom(Coord coord);

}

That should help you because it decouples locations from administrative tasks - if you were writing C your approach would be a good one. 那应该对您有帮助,因为它使位置与管理任务脱钩了-如果您正在编写C,那么您的方法将是一个不错的选择。 But you're writing Java. 但是您正在编写Java。

Moreover: The for loop will silently fail because you deplete the iterator without checking for a hasNext() . 而且: for循环将静默失败,因为您无需检查hasNext()耗尽了iterator That's only done at the outer loop. 这仅在外循环中完成。 So 所以

int i=0;
while(iterator.hasNext() && iterator1.hasNext()){ //also check iterator1
     if(i>=144) break; //that's what your for loop essentially did
        double distance = 0;  
        double lat_end = 0;
        double lon_end = 0;

        try {
            lat_end = Double.parseDouble(iterator.next());
            lon_end = Double.parseDouble(iterator1.next());
            CoordArray.add(new Coord(lat_end, lat_long));
            Log.i("Lon_end", String.valueOf(lon_end));

        } catch (NumberFormatException e) { ... }
//more stuff here
i++;
}/*while loop*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM