Skip to content

Instantly share code, notes, and snippets.

@rmg007
Created October 16, 2022 15:11
Show Gist options
  • Save rmg007/f57fb7105cc36257243867bd73652788 to your computer and use it in GitHub Desktop.
Save rmg007/f57fb7105cc36257243867bd73652788 to your computer and use it in GitHub Desktop.
Sort String List By Length
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class SortStringListByLength {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("Byyyyyyyyyyyy", "Dww", "Cxxxxxx", "az"));
Comparator<String> lengthComparator = Comparator.comparingInt(String::length);
Comparator<String> lengthComparator2 = (s1, s2) -> Integer.compare(s1.length(), s2.length());
list.sort(lengthComparator);
// OR
list.sort(lengthComparator2);
System.out.println(list);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment