Java:如何对两个对应的数组进行排序?

编程入门 行业动态 更新时间:2024-10-25 07:33:51
本文介绍了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 Integerpare(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:如何对两个对应的数组进行排序?

本文发布于:2023-11-30 10:57:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649728.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   两个   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!