二维数组按输入然后第二个排序

这可能是一个相当基本的问题,但我似乎无法在线找到我需要的答案。


但是,对二维数组排序的最佳方法是什么?


我有一个预填充的二维数组'mainArr [] []',其中包含数据:


John Doe - 678DGHJ,Sport

Lisa Parker - 432KH3,Car

John Doe - 678DGHJ, Drive

Peter Bear 4HJ4K3,Bus

John Doe - 4HJK4,Loose

逗号是数组中维之间的分隔符。如何首先按数组中的列对其进行排序,然后按数组第二部分中的值对其进行排序。


上面排序的数据将变为:


John Doe - 4HJK4,Loose

John Doe - 678DGHJ,Drive

John Doe - 678DGHJ,Sport

Lisa Parker - 432KH3,Car

Peter Bear 4HJ4K3,Bus

所以排序数组中的数据


mainArr[0][0] 

等于


mainArr[John Doe - 4HJK4][Loose]


胡子哥哥
浏览 187回答 1
1回答

千巷猫影

您可以使用Comparator如下所示对数组进行排序,import java.util.Arrays;import java.util.Comparator;public class Main {&nbsp; &nbsp; public static void main(String args[]) {&nbsp; &nbsp; &nbsp; &nbsp; String[][] mainArr = new String[][] {{"John Doe - 678DGHJ", "Sport"}, {"Lisa Parker - 432KH3", "Car"}, {"John Doe - 678DGHJ", "Drive"}, {"Peter Bear 4HJ4K3", "Bus"}, {"John Doe - 4HJK4", "Loose"}};&nbsp; &nbsp; &nbsp; &nbsp; Arrays.sort(mainArr, new Comparator<String[]>() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public int compare(String[] entry1, String[] entry2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (entry1[0].equals(entry2[0])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return entry1[1].compareTo(entry2[1]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return entry1[0].compareTo(entry2[0]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < mainArr.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(mainArr[i][0] + ", " + mainArr[i][1]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java