Java如何对ArrayList的项目进行排序?
此示例说明如何ArrayList使用Collections.sort()方法对的项目进行排序。除了接受要排序的列表对象之外,我们还可以传递一个Comparator实现来定义排序行为,例如按降序或升序排序的实现。
package org.nhooo.example.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ArrayListSortExample { public static void main(String[] args) { /* * Create a collections of colours */ List<String> colours = new ArrayList<>(); colours.add("red"); colours.add("green"); colours.add("blue"); colours.add("yellow"); colours.add("cyan"); colours.add("white"); colours.add("black"); /* * We can sort items of a list using the Collections.sort() method. * We can also reverse the order of the sorting by passing the * Collections.reverseOrder() comparator. */ Collections.sort(colours); System.out.println(Arrays.toString(colours.toArray())); Collections.sort(colours, Collections.reverseOrder()); System.out.println(Arrays.toString(colours.toArray())); } }
该代码将输出:
[black, blue, cyan, green, red, white, yellow] [yellow, white, red, green, cyan, blue, black]