如何按升序对数字数组列表进行排序 [英] how to sort numerical arraylist in ascending order

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

问题描述

我有一个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中,您可以使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆