简体   繁体   中英

Sort an ArrayList based on Priorities obtained from a Map (Java version < Java8)

What would be the best way to sort an ArrayList that has Strings according to the priorities obtained from a map.

For eg: I have a Map with priorities assigned for specific use case (Key: pattern that I am looking for in the String and Value: Priority for that pattern)

Map pMap= new HashMap();
pMap.put("", 1);
pMap.put("1", 2);
pMap.put("2", 3);
pMap.put("3", 4);
pMap.put("4", 5);
pMap.put("*", 6);

List<String> listToBeSorted= new ArrayList<>();
listToBeSorted.add("Axxxx");
listToBeSorted.add("Ax4xx");
listToBeSorted.add("px*xxx");
listToBeSorted.add("px1xx");

I want to assign priority for each string in the list based on 3rd character, sort the list based on the priorities obtained.

My Approach :

Take the listToBeSorted, iterate over that and get the priority for each string and insert into a Temp Hashmap with the key being the String and value being its Priority. Finally return the new Arraylist with sorted keys.

Result expected: Arraylist that contains following data:

Axxxx
px1xx
Ax4xx
px*xxx

This approach works for now but I don't think this is a good approach when there is high volume of data.

Is there a better way to solve this problem?

PS: I know there is a better solution in Java 8. But unfortunately I am unable to use it.So it would be great if someone could give me a better solution which is not in Java8?

Thank you in advance for your time.

You just need a comparator that compares two strings based on their priorities:

Comparator<String> priorityBasedComparator = new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        int priority1 = pMap.get(s1.substring(2, 3));
        int priority2 = pMap.get(s2.substring(2, 3));
        return Integer.compare(priority1, priority2);
    }
}
Collections.sort(list, priorityBasedComparator);

Of course, pMap should be declared as a Map<String, Integer> and not as a raw Map (you should never use raw types). And it should be final to be usable from the comparator.

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