Recently, I've been declining in the WEB coding test for job change activities. I'm practicing at paiza.io because I think I have to get used to it. If you are too busy to solve it, you will see the source at a later date and mass-produce the nauseating fucking code.
This time, I will summarize the method of sorting after storing in List
java.util.Comparator;Imagine you are importing.
# Alphabetical order
```java
List<String> list = Arrays.asList("ABC", "DEFGH", "IJKL", "abc", "defgh", "ijkl");
//Alphabetical ascending order (case insensitive)
//Output result: ABC,abc,DEFGH,defgh,IJKL,ijkl
list.sort(String.CASE_INSENSITIVE_ORDER);
//Descending alphabetical order (case insensitive)
//Output result: IJKL,ijkl,DEFGH,defgh,ABC,abc
list.sort(String.CASE_INSENSITIVE_ORDER.reversed());
//Alphabetical ascending order (case sensitive)
//Output result: ABC,DEFGH,IJKL,abc,defgh,ijkl
list.sort(Comparator.naturalOrder());
//Descending alphabetical order (case sensitive)
//Output result: ijkl,defgh,abc,IJKL,DEFGH,ABC
list.sort(Comparator.reverseOrder());
List<String> list = Arrays.asList("ABC", "DEFGH", "IJKL", "abc", "defgh", "ijkl");
//Ascending order of string length
//Output result: ABC,abc,IJKL,ijkl,DEFGH,defgh
list.sort(Comparator.comparingInt(String::length));
//String length descending
//Output result: DEFGH,defgh,IJKL,ijkl,ABC,abc
list.sort(Comparator.comparingInt(String::length).reversed());
Character string length → Sort alphabetically
list.sort(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()));
How to sort Integer.
List<Integer> list = Arrays.asList(1, 3, 2);
//ascending order
Collections.sort(list);
//descending order
Collections.reverse(list);
It can be realized with Lambda, but I personally feel that Comparator is more readable, so I omitted it. I want to come out quickly without investigating this much.
Coding tests often require this sort of sorting, so it's a good idea to remember! This one is more readable! Please let us know if you have any opinions or mistakes.
Recommended Posts