如何在Java中的多个阵列排序 [英] How to sort multiple arrays in java

查看:188
本文介绍了如何在Java中的多个阵列排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想三个阵列通过字典顺序排序。该阵列是由一个共同的阵列彼此相关。它更容易解释,如果我证明:

I'm trying to sort three arrays by lexicographical order. The arrays are related to each other by a common array. It's easier to explain if I demonstrate:

int[] record = new int[4];
String [] colors = {"blue", "yellow", "red", "black"};
String [] clothes = {"shoes", "pants", "boots", "coat"};

在控制台上打印出来,我想他们放在三列类似如下:

When printed on the console, I would like them to be put in three columns similar to below:

Record  Color   Clothes
0       blue    shoes
1       yellow  pants
2       red     boots
3       black   coat

按颜色排序:

Record  Color   Clothes
3       black   coat
0       blue    shoes
2       red     boots
1       yellow  pants

按衣服排序方式:

Record  Color   Clothes
2       red     boots
3       black   coat
1       yellow  pants
0       blue    shoes

我发现了一个previous回答类似于我的方案,但它比较整数,而不是字符串,我使用的compareTo()方法有麻烦, Arrays.sort()在我需要的输出到达。

I found a previous answer similar to my scenario, but it compared integers instead of strings, and I'm having trouble using the compareTo() method and Arrays.sort() to arrive at my desired output.

任何帮助将是AP preciated!

Any help would be appreciated!

推荐答案

由于录制颜色衣服似乎属于在一起,我会建议在自定义对象一起移动它们,如:

Since Record, Color and Clothes seem to belong together, I would suggest moving them together in a custom Object, eg

public class ClothesItem {
    int record;
    String color;
    String clothes;
}  

然后你就可以做出不同的 比较 s到做排序的不同变种。

Then you can make different Comparators to do the different variants of sorting.

如果您需要preserve当前的结构与多个阵列, @Jherico有一个排序的解决方案,这里了得到分类指标组成的数组,这应该让平凡到你想要的结果。

If you need to preserve your current structure with multiple arrays, @Jherico has a sorting solution here that gets an array of the sorted indexes, which should make it trivial to get to your wanted result.

这篇关于如何在Java中的多个阵列排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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