Java:如何对两个对应的数组进行排序? [英] Java: How to sort two corresponding arrays?

查看:107
本文介绍了Java:如何对两个对应的数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

First array:
25, 20, 50, 30, 12, 11...

Second Array: 
New York, New Jersey, Detroit, Atlanta, Chicago, Los Angeles

第二个数组中的每个城市对应于第一个数组中的一个值.

Every two cities from the second array correspond to one value from the first.

示例:纽约和新泽西对应25,底特律和亚特兰大对应20,依此类推.

Example: New York and New Jersey would correspond to 25, Detroit and Atlanta would correspond to 20 and so on.

我想按降序(50、30、25、20 ...)对第一个数组的数字进行重新排序,但我也希望对第二个数组的城市进行相应的移动,以使它们在和之前具有相同的值.排序之后.

I want to reorder the first Array's numbers in descending order (50, 30, 25, 20...), but I also want the cities of the second array to be shifted accordingly so that they have the same value before and after the sort.

如何完成此任务?(我可以使用ArrayList或Array,以较简单的方法为准)

How do I accomplish this task? (I can use either an ArrayList or an Array, whichever works out simpler)

推荐答案

您可以使用TreeMap:

You can use TreeMap:

Map<Integer, String[]> map = new TreeMap<>();
for(int i=0;i<firstArray.length;i++){
   map.put(firstArray[i], new String[]{secondArray[i * 2], secondArray[i*2+1]});
}

此地图将按关键的自然顺序排序.

And this map will be sorted by key natural order.

但是我建议您进行容器类的学习.像这样:

But I would suggest you to make container class. Something like:

public class CityPair{
  public int value;
  public String[] cities = new String[2]; 
}

现在,您可以按数据填写列表:

Now you can fill the list by your data:

...   
ArrayList list = new ArrayList<CityPair>();

for(int i=0; i<firstArray.length; i++){
  CityPair pair = new CityPair();
  pair.value = firstArray[i];
  pair.cities[0] = secondArray[i*2];
  pair.cities[1] = secondArray[i*2+1];
  list.add(pair);
}
...

如您所见,我没有检查索引是否为索引超出范围",但是您应该这样做.之后,您可以对列表进行排序.您可以使用例如气泡排序算法手动完成操作,但是更好的方法是编写自定义比较器:

As you see, I didn't check indexes for "index out of bounds", but you should. After that you can sort your list. You could do it manually using for example Bubble sort algorithm, but better way is write custom comparator:

public class CityPairComparator implements Comparator<CityPair> {
    @Override
    public int compare(CityPair pair1, CityPair pair2) {
        return Integer.compare(pair1.value, pair2.value);
    }
}

现在您可以使用Collections实用程序类对列表进行排序:

Now you can sort your list with Collections utility class:

Collections.sort(list, new CityPairComparator());

使用此方法,您可以将 CityPair 类中的 String []城市替换为 ArrayList< Sting>.城市.这样就可以为每个值添加两个以上的城市.

With this approch you can replace String[] cities in CityPair class for ArrayList<Sting> cities. Then it's will be able to add more than two cities per value.

这篇关于Java:如何对两个对应的数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆