Java.Java8.How can I sort a list of strings using a lambda expression?

Basic Example – Sort Strings Alphabetically

List<String> names = Arrays.asList("Charlie", "Alice", "Bob");

names.sort((s1, s2) -> s1.compareTo(s2));  // ascending order
System.out.println(names); // [Alice, Bob, Charlie]

Java’s List.sort() method expects a Comparator, and the lambda provides the comparator logic inline.


Even Better – Using Method Reference

If you’re just doing a straightforward sort:

names.sort(String::compareTo);

Same result — just cleaner and more readable.

🔁 Descending Order Sort

names.sort((s1, s2) -> s2.compareTo(s1));  // descending
System.out.println(names); // [Charlie, Bob, Alice]

🧠 Bonus – Sort by Length of Strings

names.sort((s1, s2) -> Integer.compare(s1.length(), s2.length()));
System.out.println(names); // [Bob, Alice, Charlie]

Or with a method reference and comparator chaining:

names.sort(Comparator.comparingInt(String::length));
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.