【Java登神长阶】Arrays.sort()

一、对一维数组使用

1.对数组从小到大进行升序排序

Arrays.sort(int[] a)

🌰

public static void main(String[] args) {
    int[] nums={1,3,5,7,9,2,4,6,8,10};
    Arrays.sort(nums);
    for (int num:nums) {
        System.out.print(num+" ");
    }
}
//结果:1 2 3 4 5 6 7 8 9 10 

2.对数组的部分内容进行从小到大排序

Arrays.sort(int[] a, int fromIndex, int toIndex)

🌰

public static void main(String[] args) {
    int[] nums={1,3,5,7,9,2,4,6,8,10};
    Arrays.sort(nums,1,9);
    for (int num:nums) {
        System.out.print(num+" ");
    }
}
//结果:1 2 3 4 5 6 7 8 9 10 

3.重写比较器,实现从大到小排序

🌰

public class MyComparator implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        if(o1<o2)
            return 1;
        else if(o1>o2)
            return -1;
        else
            return 0;
    }
}
public class Solution {
    public static void main(String[] args) {
        Integer[] nums={1,3,5,7,9,2,4,6,8,10};

        Comparator cmp=new MyComparator();
        Arrays.sort(nums,cmp);
        for (int num:nums) {
            System.out.print(num+" ");
        }
    }
}
//结果:10 9 8 7 6 5 4 3 2 1 
🐒Comparator源码
@FunctionalInterface
public interface Comparator<T> {
    /**
     * Compares its two arguments for order.  Returns a negative integer,
     * zero, or a positive integer as the first argument is less than, equal
     * to, or greater than the second.
     * 译:对两个参数进行排序,当第一个参数<、=、>第二个参数时,分别返回负数、0、正数。
     */
    int compare(T o1, T o2);
}

默认的Comparator比较器对于两个操作数o1,o2

对两个参数进行排序,当第一个参数<、=、>第二个参数时,分别返回负数、0、正数。

现在改写为当第一个参数<第二个参数时,返回正数。

🔵lambda表达式
public class Solution {
    public static void main(String[] args) {
        Integer[] nums={1,3,5,7,9,2,4,6,8,10};
        
        Arrays.sort(nums,((o1, o2) -> (o2-o1)));
        for (int num:nums) {
            System.out.print(num+" ");
        }
    }
}
//结果:10 9 8 7 6 5 4 3 2 1 

二、对二维数组使用

1.第一个元素升序排序

public class Solution {

    public static void main(String[] args) {
        int[][] nums={{1,3},{3,1},{5,4},{2,2}};

        Arrays.sort(nums,((o1, o2) -> (o1[0]-o2[0])));

        for(int i=0;i< nums.length;i++)
            System.out.println(Arrays.toString(nums[i]));
    }
}

2.第一个元素降序排序

Arrays.sort(nums,((o1, o2) -> (o2[0]-o1[0])));

3.按照第二个元素升序排序

Arrays.sort(nums,((o1, o2) -> (o1[1]-o2[1])));

4.按照第二个元素降序排序

Arrays.sort(nums,((o1, o2) -> (o2[1]-o1[1])));

觉得本篇对您有帮助的,请留下一个大大的👍🏼赞,这对我真的很重要!
请添加图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

童锣烧tls

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值