数组排序
1. 数组排序(从小到大排序)
import java.util.Arrays; public class Test01 { public static void main(String[] args){ // 数组(从小到大排序) // 1.第一种方法 Integer[] arr1 = {21,11,41,31,51}; Arrays.sort(arr1); System.out.println(Arrays.toString(arr1)); // [11, 21, 31, 41, 51] // 2.第二种方法(从大到小排序) Integer[] arr2 = {21,11,41,31,51}; Arrays.sort(arr2, (a, b) -> { return a - b; }); System.out.println(Arrays.toString(arr2)); // [11, 21, 31, 41, 51] } }
2. 数组排序(从大到小排序)
import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; public class Test01 { public static void main(String[] args){ // 数组(从小到大排序) // 1.第一种方法 Integer[] arr3 = {11,21,31,41,51}; Arrays.sort(arr3, (a, b) -> { return b - a; }); System.out.println(Arrays.toString(arr3)); // [51, 41, 31, 21, 11] // 2.第二种方法,数组反转 Integer[] arr4= {11,21,31,41,51}; // 数组转ArrayList ArrayList<Integer> arrayList = new ArrayList<Integer>(Arrays.asList(arr4)); Collections.reverse(arrayList); // ArrayList转数组 arr4 = arrayList.toArray(new Integer[arrayList.size()]); System.out.println(Arrays.toString(arr4)); // [51, 31, 41, 11, 21] } }
ArrayList排序
1. ArrayList排序(从小到大排序)
import java.util.ArrayList; import java.util.Collections; public class Test01 { public static void main(String[] args){ // ArrayList排序(从小到大排序) // 1.第一种方法 ArrayList<Integer> arrayList = new ArrayList<Integer>(){{add(21);add(11);add(41);add(31);add(51);}}; Collections.sort(arrayList); System.out.println(arrayList); // [11, 21, 31, 41, 51] // 2.第二种方法 ArrayList<Integer> arrayList2 = new ArrayList<Integer>(){{add(21);add(11);add(41);add(31);add(51);}}; Collections.sort(arrayList2, (a, b) -> { return a - b; }); System.out.println(arrayList2); // [11, 21, 31, 41, 51] } }
2. ArrayList排序(从大到小排序)
import java.util.ArrayList; import java.util.Collections; public class Test01 { public static void main(String[] args){ // ArrayList排序(从大到小排序) // 1.第一种方法 ArrayList<Integer> arrayList3 = new ArrayList<Integer>(){{add(21);add(11);add(41);add(31);add(51);}}; Collections.sort(arrayList3, (a, b) -> { return b - a; }); System.out.println(arrayList3); // [51, 41, 31, 21, 11] // 2.第二种方法 ArrayList<Integer> arrayList4 = new ArrayList<Integer>(){{add(21);add(11);add(41);add(31);add(51);}}; Collections.sort(arrayList4); Collections.reverse(arrayList4); System.out.println(arrayList4); // [51, 41, 31, 21, 11] } }
标签:11,Java,21,ArrayList,51,41,add,排序 From: https://www.cnblogs.com/REN-Murphy/p/17911351.html