仅使用绝对值对Array进行排序并显示实际值 [英] Sort the Array with Absolute value only and show real value
本文介绍了仅使用绝对值对Array进行排序并显示实际值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
打印绝对排序数组。请参阅示例输出以获得说明。
输入:
9 -2 10 3 -5 34 -22 7
我想要输出:
-2 3 -5 7 9 10 -22 34
我尝试使用 Arrays.sort(a []);
请帮帮我:
谢谢
推荐答案
使用Java 8,你可以像这样使用lambda和Math.abs:
With Java 8, you can use lambda and Math.abs like this:
Integer[] array = {9,-2,10,3,-5,34,-22,7};
Arrays.sort(array, (a,b) -> (Integer.compare( Math.abs(a), Math.abs(b))));
Stream.of(array).forEach(a -> System.out.println(a));
感谢4castle的建议。或者使用Comparator
Thanks to 4castle for suggestion. Or use Comparator
Arrays.sort(array, Comparator.comparingInt(Math::abs));
这篇关于仅使用绝对值对Array进行排序并显示实际值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文