打印一个从大到小、从小到大的数字列表



如何通过从最小到最大或从最大到最小排序来输出列表的值?

private static final ArrayList<Double> nbAll = new ArrayList<>();
public static void test() {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Please enter the number of notes you want to calculate : ");
double nb = scanner.nextInt();
for (int i = 0; i < nb; i++) {
double temp = scanner.nextDouble();
nbAll.add(temp);
}
double temp = nbAll.stream().mapToInt(Double::intValue).sum();
double result = temp / nb;
System.out.println("Result : " + result);
retry();
}
}

对列表的元素进行流式处理,排序,然后打印:

nbAll.stream().sorted().forEach(System.out::println);

按反向排序:

nbAll.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);

可以调用Collections.sort

Collections.sort(nbAll); // ascending order
nbAll.forEach(System.out::println);

然后按降序打印它们,不需要使用,只需要从末尾开始,按倒序打印它们。

for (int i = nbAll.size()-1; i >= 0; i--) {
System.out.println(nbAll.get(i));
}

最新更新