4 tricks to get Java List sorted

In the development of ERP or e-commerce systems, functional scenarios such as content encryption, signature generation, and page list display are often encountered. At this time, we need to sort the List collection in the Java program.

 

There are four common methods of sorting:

1. Use Comparable to sort;

2. Use Comparator to sort;

3. For environments above JDK 8 , Stream can be used for sorting;

4. After JDK8 , especially the prevalence of lambda expressions, and the sort method of Collections actually calls the sort method of the List interface itself; so you can use the sort method of the List interface itself to sort.

 

This article will take how two different development forms implement List sorting through Comparator and Collection.sort as an example.

 

  1. Manual writing: use Comparator to sort

When an intermediate Java development engineer encounters a List sorting requirement, he chooses to use the Comparator method that can sort different types of objects without implementing the sorting algorithm by himself. It usually takes about 15 minutes.

code show as below:

public static void sort(List<Map<String, Object>> list, String columns, String order) {

    String[] arrCols = columns.split(REGEX);

    Stream<Map<String, Object>> stream = list.stream();

    Comparator<Map<String, Object>> comparator = getMapComparator(list, arrCols, order);

    List<Map<String, Object>> updateList =    stream.sorted(comparator).collect(Collectors.toList());

    list.clear();

    list.addAll(updateList);

}

 

private static Comparator<Map<String, Object>> getMapComparator(List<Map<String, Object>> list, String[] arrCols, String order) {

    Comparator<Map<String, Object>> comparator;

    if (list.get(0).get(arrCols[0]) instanceof Integer) {

        comparator = Comparator.comparingInt((Map<String, Object> map) -> Integer.valueOf(map.get(arrCols[0]).toString()));

    } else if (list.get(0).get(arrCols[0]) instanceof Long) {

        comparator = Comparator.comparingLong((Map<String, Object> map) -> Long.valueOf(map.get(arrCols[0]).toString()));

    } else if (list.get(0).get(arrCols[0]) instanceof Double) {

        comparator = Comparator.comparingDouble((Map<String, Object> map) -> Double.valueOf(map.get(arrCols[0]).toString()));

    } else {

        comparator = Comparator.comparing((Map<String, Object> map) -> String.valueOf(map.get(arrCols[0])));

    }

    // descending

    if (order.equals(ORDER_DESC)) {

        comparator = comparator.reversed();

    }

    // exclude the first

    for (int i = 1; i < arrCols.length; i++) {

        int f = i;

        if (list.get(0).get(arrCols[f]) instanceof Integer) {

            comparator = comparator.thenComparingInt((Map<String, Object> map) -> Integer.valueOf(map.get(arrCols[f]).toString()));

        } else if (list.get(0).get(arrCols[f]) instanceof Long) {

            comparator = comparator.thenComparingLong((Map<String, Object> map) -> Long.valueOf(map.get(arrCols[f]).toString()));

        } else if (list.get(0).get(arrCols[f]) instanceof Double) {

            comparator = comparator.thenComparingDouble((Map<String, Object> map) -> Double.valueOf(map.get(arrCols[f]).toString()));

        } else {

            comparator = comparator.thenComparing((Map<String, Object> map) -> String.valueOf(map.get(arrCols[f])));

        }

        // If it is descending order, set descending order every time

        if (order.equals("desc")) {

            comparator = comparator.reversed();

        }

    }

    return comparator;

}

 

  1. FuncGPT ( Hui function) function AI generator: use Collection.sort to sort

Collection.sort() is used to sort the collection. The sort is similar to the bubble sort. The sort method is to continuously traverse the List, compare any two adjacent elements of the List, and see if the two adjacent elements are exchanged. . If any two elements in the List are not exchanged, the sorting is over.

See how FuncGPT implements List sorting through Collection.sort:

Enter specific requirements and parameter requirements in the user interface:

Function function : List sorting

Parameter 1 : Parameter name: list; Parameter type: List<Map<String, Object>>; Parameter description: List object

Parameter 2 : Parameter name: columns; Parameter type: String; Parameter description: sorting field names, separated by /;

Parameter 3 : parameter name: order; parameter type: String; parameter description: sorting category asc order, desc reverse order

Return value : not null

  1. Summarize

This article introduces two methods of List sorting. Comparator is often used in versions before JDK 8, and in versions after JDK 8, you can use Collection.sort to implement sorting.

In addition, it is worth mentioning that the two List sorting methods are realized in two different forms by manual writing and FuncGPT (wisdom function) function AI generator. If you compare and analyze these two codes, you will find:

1. In terms of efficiency, the original manual coding took about 15 minutes, but the AI ​​tool only took 24 seconds, and the second-level function generation, the efficiency has been greatly improved;

2. The manually written code has a complex structure, including conditional judgment and logical branching; while AI tools use the Collection.sort method for sorting, which is intuitive and simple, and the code readability is better than manual coding;

3. The manually written code does not judge null values ​​or spaces, and there are loopholes, while the AI ​​tool uses the StringUtils tool class in the Apache Commons Lang library to judge whether an expression is empty or a space, and the robustness of the code is better.

As an important part of the SoFlu software robot, FuncGPT (wit function) supports the creation of all types of functions. Describe Java function requirements through natural language, and generate high-quality, highly readable Java function codes in real time. The generated code can be directly copied to IDEA, or imported into the Java fully automatic development tool function library with one click.

 

FuncGPT (intelligent function) is open for free, click the link http://suo.im/aREPi to download and install.

The Indian Ministry of Defense self-developed Maya OS, fully replacing Windows Redis 7.2.0, and the most far-reaching version 7-Zip official website was identified as a malicious website by Baidu. Go 2 will never bring destructive changes to Go 1. Xiaomi released CyberDog 2, More than 80% open source rate ChatGPT daily cost of about 700,000 US dollars, OpenAI may be on the verge of bankruptcy Meditation software will be listed, founded by "China's first Linux person" Apache Doris 2.0.0 version officially released: blind test performance 10 times improved, More unified and diverse extremely fast analysis experience The first version of the Linux kernel (v0.01) open source code interpretation Chrome 116 is officially released
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/4868096/blog/10097046
Recommended