Java Using Comparators in combination with custom Comparators

ShadowDragon :

I want to sort the following example list which currently contains only Strings with my own custom rules.

ArrayList<String> coll = new ArrayList<>();
coll.add("just");
coll.add("sdsd");
coll.add("asb");
coll.add("b as");
coll.add("just");
coll.add("dhfga");
coll.add("jusht");
coll.add("ktsa");
coll.add("just");
coll.add("just");

I know that I could write my own comparator for this, but as I know that Java also got comparators which solve this problem partially I want to know how I can use the ones from the Java API in combination with my own one.


How should it be sorted?

The word just should always be the first word to appear in the list followed by all other words in alphabetical order.

Comparator.naturalOrder() sorts the list in alphabetical order, but how can I combine this comperator with a custom one which checks whether the word is just or something else.

ZhekaKozlov :

You can do this something like that:

coll.sort(Comparator
    .comparingInt((String s) -> s.equals("just") ? 0 : 1) // Words "just" first
    .thenComparing(Comparator.naturalOrder())); // Then others

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=473709&siteId=1