Created
October 16, 2022 15:11
-
-
Save rmg007/f57fb7105cc36257243867bd73652788 to your computer and use it in GitHub Desktop.
Sort String List By Length
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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