简体   繁体   中英

Sort a list in java into a specific order

What is the best way to implement a custom sort for a List?

I have the List of Constants below.

ENERGY_POLICY, OBJECTIVE, TRAINING, SEU_REPORT, ENERGY_PERFORMANCE, INTERNAL_AND_EXTERNAL_PARTIES, INTERNAL_AUDIT_REVIEW, LEGAL_REQUIREMENTS_REVIEW, TASKS_REVIEW, CORRECTIVE_ACTIONS

I would like to implement a sort function to sort them in the specific order shown below.

[OBJECTIVE, ENERGY_POLICY, TRAINING, ENERGY_PERFORMANCE, INTERNAL_AUDIT_REVIEW, LEGAL_REQUIREMENTS_REVIEW, TASKS_REVIEW, SEU_REPORT, CORRECTIVE_ACTIONS, INTERNAL_AND_EXTERNAL_PARTIES]

Any help pointing me in the right direction would be greatly appreciated.

You can try something like this


        List<String> strings = Arrays.asList("OBJECTIVE", "ENERGY_POLICY", "TRAINING", "ENERGY_PERFORMANCE", "INTERNAL_AUDIT_REVIEW",  "LEGAL_REQUIREMENTS_REVIEW", "TASKS_REVIEW, SEU_REPORT", "CORRECTIVE_ACTIONS", "INTERNAL_AND_EXTERNAL_PARTIES");

        Map<String, Integer> ranks = new HashMap<>();

        // Assign rank to each element and store in ranks map. This map will be used for retrieving rank of each element while defining custom sorter
        for (int i =0 ; i< strings.size() ; i++) {
            ranks.put(strings.get(i),i);
        }

        // Now lets take a list which needs to sorted based on above order
        List<String> stringsToBeSorted  = Arrays.asList("ENERGY_POLICY", "OBJECTIVE", "TRAINING", "SEU_REPORT", "ENERGY_PERFORMANCE", "INTERNAL_AND_EXTERNAL_PARTIES", "INTERNAL_AUDIT_REVIEW", "LEGAL_REQUIREMENTS_REVIEW", "TASKS_REVIEW", "CORRECTIVE_ACTIONS");

        stringsToBeSorted.sort(new Comparator<String>() {
            @Override
            public int compare(String str1, String str2) {
                if (ranks.get(str1) == null || ranks.get(str2) == null) {
                    return 0;
                }

                return ranks.get(str1) - ranks.get(str2);
            }
        });


Or with Java 8

        stringsToBeSorted.sort(Comparator.comparingInt(ranks::get));  

But you need to make sure that strings has all the values and there should be no value in stringsToBeSorted list which is not present in strings list. as it will throw null pointer exception as its rank retrieved from hashmap is null

You can put each constant in a hash map with the constant as key and the position as the value.

now as and when you receive the constants get the position it should be from the hashmap and based on it create the final list

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