In Java 8, we will organize the sorting method of List.
Java 7 and below
Review of the Java 7 era
List<String> nameList = Arrays.asList("Takahashi", "Tanaka", "Suzuki");
Collections.sort(nameList);
Starting with Java 8, sort (Comparator) has been added to List and you can use it to sort the list.
nameList.sort(Comparator.comparingInt(String::length));
Sort by multiple conditions (string length-> alphabetical order). You can add sort conditions by using thenComparing ().
nameList.sort(Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()));
Also, with the introduction of Stream, you can source lists with Stream # sorted.
List<String> sortedList = nameList.stream().sorted()
.collect(Collectors.toList());
Sort by string length.
List<String> sortedList = nameList.stream().sorted((s1, s2) -> s1.length() - s2.length())
.collect(Collectors.toList());
Sort alphabetically.
List<String> sortedList = nameList.stream().sorted((s1, s2) -> s1.compareTo(s2))
.collect(Collectors.toList())
Sort by string length.
List<String> sortedList = nameList.stream().sorted(
Comparator.comparingInt(String::length)).collect(Collectors.toList());
Sort alphabetically.
List<String> sortedList = nameList.stream().sorted(
Comparator.naturalOrder()).collect(Collectors.toList())
String length-> Sort alphabetically. You can add sort conditions by using thenComparing ().
List<String> sortedList = nameList.stream().sorted(
Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder())).collect(Collectors.toList());
List<Person> sortedList = personList.stream().sorted(new Comparator<Person>(){
@Override
public int compare(Person o1, Person o2) {
return o1.getName().compareTo(o2.getName());
}
}).collect(Collectors.toList());
Recommended Posts