use*_*394 -1 java sorting arraylist
I have a String list of numbers (they can be an int list, just need to turn it into an array list to return), this numbers can be from a range, for example from 1 to 25.
I tried sorting them using Collections.sort(numbersList); but it sorts them in a weird way. For example this is the current sorting:
1
10
11
..
2
20
21
..
Run Code Online (Sandbox Code Playgroud)
What I really want is for it to be sorted in a numerical order, for example:
1
2
3
..
10
11
..
Run Code Online (Sandbox Code Playgroud)
Tried to sort them as an int[] with Arrays.sort(numbers); but it gives the same result.
Here is the code that I use to generate the numbers and turn them into an array list.
int[] range = IntStream.rangeClosed(1, 30).toArray();
Arrays.sort(range);
List<String> rangeList = new ArrayList<>();
for (int number : range) {
rangeList.add(String.valueOf(number));
}
Run Code Online (Sandbox Code Playgroud)
I feel like I've seen this before, but you can try the following in Java 8+ (where numbersList is the String[]):
Arrays.sort(numbersList, Comparator.comparing(Integer::valueOf));
Run Code Online (Sandbox Code Playgroud)
Additionally, in your code, you have a problem in your initialization of range, because the parenthesis for Integer.parseInt is not closed, and the parameters are wrong. It should be replaced with the following:
int[] range = IntStream.rangeClosed(1, 30).toArray();
Run Code Online (Sandbox Code Playgroud)
完成此操作后,您无需进行排序,因为IntStream.rangeClosed保证将按排序顺序提供IntStream中的所有元素。如果您想了解有关如何正确使用Integer.parseInt的更多信息,我强烈建议您查看Javadoc。
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |