(Leetcode)将数组按照绝对值大小从大到小排序

发布时间 2023-06-20 15:51:55作者: 杨百顺

【少说多做,少想多做】

 nums = IntStream.of(nums).
        boxed().
        sorted((o1,o2)->Math.abs(o2)-Math.abs(o1))
        .mapToInt(Integer::intValue).toArray();
  • IntStream.of(nums)将int数组转换成一个IntStream类型的流。
  • 通过boxed()方法将IntStream流中的每个元素都转换成一个对应的Integer对象,从而将流转换成一个Stream类型的流。
  • 通过sorted((o1,o2)->Math.abs(o2)-Math.abs(o1))方法对Stream类型的流进行排序。排序使用的比较器是一个Lambda表达式(o1,o2)->Math.abs(o2)-Math.abs(o1),该表达式根据o1和o2的绝对值之差来进行比较。因为要按照绝对值从大到小排序,所以o2的绝对值大于o1的绝对值时,返回负值,否则返回正值。
  • 通过mapToInt(Integer::intValue)将Stream类型的流转换成一个intStream类型的流。通过toArray()方法将IntStream类型的流转换成一个int类型的数组。

参考博客:
https://blog.csdn.net/qq_42467430/article/details/129953955
https://programmercarl.com/