以相同的方式对 2 个数组进行排序

Sort 2 arrays by the same way

我有两个未排序的数组:一个浮点数组 (float[]) 和一个用于描述的 String 数组 (String[])。

我需要从最高值到最低值对浮点数组进行排序,但是描述在String数组中,如果我对它们进行排序,String 数组将不会进行相应排序。

Processing中,有一个sort(Array)函数,但它只对一个数组进行排序。

如何对浮点数组进行排序并使描述匹配?

float totalCount = 0;
float maxValue = 0;
String[] statusDescriptions = new String[finishStatusesJSON.size()];
float[] countData = new float[finishStatusesJSON.size()]; 
for (int i = 0; i < finishStatusesJSON.size(); i++) {
  JSONObject finishStatusJSON = (JSONObject) finishStatusesJSON.get(i);
  float count = finishStatusJSON.getFloat("count"); 
  String status = finishStatusJSON.getString("status");
  totalCount += count;
  statusDescriptions[i] = status;
  countData[i] = count;

  // Max value of the table
  if(maxValue < count) maxValue = count;

}

一种解决方案是创建一个包含您的条目的 class,即将浮点数与其描述相结合。例如,如果您将电影存储为字符串并将其分数存储为浮点数,则可以创建一个包含电影描述(字符串)及其分数(浮点数)的 class MovieScore。您可以将此设为 class Comparable,然后对 MovieScore 的数组进行排序以实现您的目标。

如何使用简单的 class 来保存两份数据并将其保存在一个数组中以便于排序。通过实施 Comparable 协议支持排序。

class Status implements Comparable<Status> {
    String  status;
    float count;

    public Status(String status, float count) {
        this.status = status;
        this.count = count;
    }

    @Override
    public int compareTo(Status s) {        
        if (this.count < s.count) {
            return 1;
        } else if (this.count > s.count) {
            return -1;
        }

        return 0;
    }
}

Status[] statusArray = new Status[finishStatusesJSON.size()];

for (int i = 0; i < finishStatusesJSON.size(); i++) {
    JSONObject finishStatusJSON = (JSONObject) finishStatusesJSON.get(i);
    Status status = new Status(finishStatusJSON.getString("status"), finishStatusJSON.getFloat("count")); 

    statusArray[i] = status;
}

Arrays.sort(statusArray);

也许你可以使用 Map<K,V> type of array, where the K would be the Float class, while the V would be the String class.

因此,您可以使用 put(K,V) 方法,如下所示,然后正确排序。

float count = finishStatusJSON.getFloat("count");
totalCount += count;

map.put( count, finishStatusJSON.getString("status") );

虽然,您似乎在谈论处理,而不是 Java。


勘误表: 直接在构造函数中使用 SortedMap implementing class; since you would be able to put a Comparator 可能更好,或者使用自然顺序,而 Map 将自行排序。

如果您仍然想使用 Map 实现 class,那么我建议您使用 MapkeySet() method, then follow the same algorithm as suggested in this answer.

但是,我对在 Processing 中使用那些 classes 持怀疑态度,因为它实际上可能对其框架无效;但如果它编译并且没有执行error/exception,那么它可能值得一试。