本文介绍了如何按升序对数值数组列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Collections.sort 排序的 ArrayList.但结果如下所示.我如何让它按升序排列?

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 包含字符串而不是数字.您可以通过传递自定义 Comparatorsort() 方法.

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 中,您可以使用 Comparator.comparingInt() 做实际比较,结合Integer.parseInt() 方法执行从字符串到整数的转换:

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));

这篇关于如何按升序对数值数组列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:05