打印从大到小和从小到大的数字列表
Print a list of numbers from largest to smallest and smallest to largest
如何输出列表中的值,从小到大或从大到小排序?
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));
}
如何输出列表中的值,从小到大或从大到小排序?
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));
}