list升序,降序,逆序
List<Integer>list =new ArrayList<Integer>();
//如果list是 5 7 2 6 8 1 4
1、升序:
Collections.sort(list) //list: 1 2 4 5 6 7 8
2、降序:
Collections.sort(list,Collections.reverseOrder())//list:8 7 6 5 4 2 1
3、逆序;
Collections.reverse(list)//list:4 1 8 6 2 7 5
数组升序,降序
int[] a={5 7 2 6 8 1 4}
1、升序:
Arrays.sort(a)//a: 1 2 4 5 6 7 8
2、降序: (一定要注意调用Collections.reverseOrder()需要是Integer[],而不是int[])
Integer[] a={5 7 2 6 8 1 4}
Arrays.sort(a,Collections.reverseOrder())//a: 8 7 6 5 4 2 1
补充:
Arrays.asList(数组)//将数组转成list
Arrays.asList(a);
List<Integer>list =new ArrayList<Integer>(Arrays.asList(a));
下面来个逆序例题
题目描述
数据很多,但我们经常只取前几名,比如奥运只取前3名。现在我们有n个数据,请按从大到小的顺序,输出前10个名数据。
数据规模和约定
10< =n< =200,各个整数不超出整型范围
输入
两行。
第一行一个整数n,表示要对多少个数据
第二行有n个整数,中间用空格分隔。表示n个数据。
输出
一行,按从大到小排列的前10个数据,每个数据之间用一个空格隔开。
样例输入
26 54 27 87 16 63 40 40 22 61 6 57 70 0 42 11 50 13 5 56 7 8 86 56 91 68 59
样例输出
91 87 86 70 68 63 61 59 57 56
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class 前10名 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Integer[] a = new Integer[n];
for(int i=0;i<n;i++)
a[i] = in.nextInt();
Arrays.sort(a, Collections.reverseOrder());
for(int i=0;i<10;i++)
if(i==9)
System.out.println(a[i]);
else
System.out.print(a[i]+" ");
}
}