博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java中二维数组按字典排序(即,按第一列排序)
阅读量:701 次
发布时间:2019-03-21

本文共 759 字,大约阅读时间需要 2 分钟。

如题,废话少说,直接上代码:

import java.util.Arrays;import java.util.Scanner;public class T_17 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[][] a = new int[n][3]; for (int i = 0; i < n; i++) {
a[i][0] = sc.nextInt(); a[i][1] = sc.nextInt(); a[i][2] = sc.nextInt(); } // 以第一列排序 Arrays.sort(a, (e1, e2) -> e1[0] - e2[0]); // 这样排序二维数组会报错 // Arrays.sort(a); for (int i = 0; i < n; i++) {
System.out.printf("%d %d %d\n", a[i][0], a[i][1], a[i][2]); } }}

结果如下:

在这里插入图片描述
还有一种方式就是转成字符串数组,然后用Arrays.sort()方法排序,但是这样还要转回来,非常麻烦。不如这样直接排序

补充:

// 按第二列排序Arrays.sort(a, (e1, e2) -> e1[1] - e2[1]);// 按第三列排序Arrays.sort(a, (e1, e2) -> e1[2] - e2[2]);// 如果要从大到小排序Arrays.sort(a, (e1, e2) -> e2[i] - e1[i]);

转载地址:http://edtez.baihongyu.com/

你可能感兴趣的文章