简体   繁体   中英

Sort arraylist of arrays based on two prioritized elements

I have an ArrayList of arrays, which I want to sort based on the arrays' two integers. I want to sort them based on a primary integer in descending order, then sort them based on one another secondary integer existing in arrays in ascending order, while maintaining the first order.

Say I have an array1 with [1, 3]; array2 with [1, 1]; array3 with [0, 50].

At first, they are unsorted in the ArrayList array1, array2 and array3. After sorting they are in order as follows: array2, array1, and array3.

you can sort the list by Collections.sort .

public void sort(List<Integer[]> list)
     return Collections.sort(list, (o1, o2) -> o1[0].equals(o2[0]) ? o1[1] - o2[1] : o1[0] - o2[0]);
}

we use Lambda expression to compare to Integer[]

when you want to sort two Integer (A,B) descendingly, you must compare them like BA and if you want to sort ascendingly, you should use AB

一个带有 java8 的单行

list.stream().sorted((prim, sec) -> prim[0] == sec[0] ? prim[1] - sec[1] : prim[0] - sec[0]).collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM