Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Collections.reverse in java to sort list collections in descending order

Shulou Source: shulou.com Published: 2022-06-02 09:29:59 10月03日 Update

This article mainly explains "how to use Collections.reverse in java to sort the list collection in descending order". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use Collections.reverse in java to sort the list collection in descending order".

Use Collections.reverse to sort the list collection in descending order

Today, I inadvertently searched Collections.reverse this method, and found that some people have a deep misunderstanding about it. Reverse can sort a specified list in descending order, but its output is not in descending order.

Indeed, it is possible to use Collections.reverse in combination with certain methods to sort list collections in descending order, but it is wrong to directly use Collections.reverse (list) to sort descending.

Reverse means reverse, not descending. It just reverses the original order of the list collection, which does not mean that the order is descending. So if you want to achieve descending order, you can first ascend the collection, and then reverse it, so it is descending.

For example:

Import java.util.*;public class Test {private static Map map = new HashMap (); public static void main (String [] args) {long [] data = {1506326821000l, 1506327060000l, 1506326880000l, 15063270000l, 1506326940000l, 1506326760000l, 150632626700l}; List list = new ArrayList (); for (long key: data) {list.add (key);} System.out.println (list); / / ascending Collections.sort (list); System.out.println (list) / / reverse Collections.reverse (list); System.out.println (list);}}

Output:

[1506326821000, 1506327060000, 1506326880000, 1506327000000, 1506326940000, 1506326760000, 1506326700000]

[1506326700000, 1506326760000, 1506326821000, 1506326880000, 1506326940000, 1506327000000, 1506327060000]

[1506327060000, 1506327000000, 1506326940000, 1506326880000, 1506326821000, 1506326760000, 1506326700000]

Collections.reverse principle public static void reverse (List list) {int size = list.size (); / / REVERSE_THRESHOLD = 18 data flashback size limit if (size

< REVERSE_THRESHOLD || list instanceof RandomAccess) { //折半处理,前后交换 //size>

> 1 equals size/2 for (int item0, mid=size > > 1, jambisizemai 1; I > 1; I

Tags: Sort learn position element content ascending order point data method result output search example principle just size that is train of thought situation meaning Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Apple vpn Docker Shulou Technology