如何按升序对数字数组列表进行排序 [英] how to sort numerical arraylist in ascending order
问题描述
我有一个ArrayList
,已使用Collections.sort
对其进行了排序.
但是结果看起来像下面这样.如何使它升序?
I have an ArrayList
which I have sorted using Collections.sort
.
But the outcome looks like down below. How do I get it to be ascending order?
[0, 1, 11, 12, 12, 13, 13, 14, 14, 16, 16, 16, 17, 17, 17, 18, 18, 19, 2, 2, 20, 20, 20, 21, 21, 22, 4, 7, 7, 7, 8, 9, 9, 9, 9, 9]
推荐答案
看起来您的ArrayList
包含字符串而不是数字.您可以通过传递自定义 Comparator
到 sort()
方法.
Looks like your ArrayList
contains strings instead of numbers. You can sort it in numerical order by passing a custom Comparator
to the sort()
method.
在Java 8中,您可以使用 Integer.parseInt()
方法来执行从字符串到int的转换:
In java 8, you can use Comparator.comparingInt()
to do the actual comparision, in combination with the Integer.parseInt()
method to perform the conversion from string to int:
ArrayList<String> list = new ArrayList<>();
// ... add values
list.sort(Comparator.comparingInt(Integer::parseInt));
这篇关于如何按升序对数字数组列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!