- How to Compare and Sort String by their length in Java? Example
- How to sort a List of String by their length in Java 7 and 8
- Java 8
- Before Java 8
- Как сравнить String по их длине в Java 7 и Java 8?
- Как отсортировать список строк по их длине в Java 7 и 8
- Как отсортировать список строк по их длине в Java 7 и 8
How to Compare and Sort String by their length in Java? Example
One of the common programming tasks is to compare String, sometimes by their value and sometimes by their length. The natural way to compare String is the lexicographic way, which is implemented in the compareTo() method of String class, but sometimes you need to compare String by their length. You cannot use the default compareTo() method for that task, you need to write your own custom Comparator , which can compare String by length. Don’t worry, It’s easy to compare multiple String by their length, all you need to do is write a Comparator implementation which calculates their length using the length() method and compares them.
Such a comparator should return a positive value if the first String has a length greater than the second String, a negative value if the length of the first string is less than the length of the second String, and zero if both String has the same length.
You can define such a one-off Comparator by using Anonymous inner class as shown in this article and further use it to sort a list of String on their length.
This is a very useful technique and works fine in Java 6 and 7 but works fantastically well in Java 8 due to less clutter provided by the brand new feature called lambda expressions.
Here is how you can do it pre Java 8 world :
public int compare(String s1, String s2) < return s1.length() - s2.length(); >
In Java 8 world, it’s even simpler by using lambda expression and new default methods added on java.util.Comparator class as shown below :
ComparatorString> strlenComp = (a, b) -> Integer.compare(a.length(), b.length());
Here are a and b are two String objects. This Integer.compare() is a new method added to Java 8. Since we are using Comparator of String, the compiler is also smart enough to infer the types of a and b, which is, of course, String.
If you are interested, please see Java 8 New Features in Simple Way to learn more about new methods added on Comparator class and several other Java 8 features which can make your day-to-day life easy.
How to sort a List of String by their length in Java 7 and 8
Here is an example of using this String length comparator to sort a list of String by their length. In this program, we have demonstrated both JDK 6 and 7 way by using Anonymous class and new Java 8 way by using lambda expressions.
Java 8
import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; /* * Java Program to sort list of String by their length in JDK 8 */ public class SortingListOfStringByLength< public static void main(String[] args) < // In Java 8 System.out.println("Sorting List of String by length in Java 8 ===== color: #3b5bb5;">ListString> cities = new ArrayList<>(Arrays.asList("London", "Tokyo", "NewYork")); System.out.println("The original list without sorting"); System.out.println(cities); cities.sort((first, second) -> Integer.compare(first.length(), second.length())); System.out.println("The same list after sorting string by length"); System.out.println(cities); > > Output Sorting List of String by length in Java 8 ====== The original list without sorting [London, Tokyo, NewYork] The same list after sorting string by length [Tokyo, London, NewYork]
You can see that the Java 8 way takes just one line and it’s a lot easier to understand once you get familiar with the syntax of lambda expressions.
If you want to learn more about lambda expression and other useful Java SE 8 features, I also suggest you join The Complete Java MasterClass which will teach you not why and how to use lambda expressions in Java 8.
Now, let’s see how you can compare String by their length in pre-Java 8 world, I mean with Java 6 and Java 7 versions.
Before Java 8
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; /* * Java Program to sort list of String by their length */ public class StringComparisonByLength< public static void main(String[] args) < ListString> books = new ArrayList<>(Arrays.asList("Effective Java", "Algorithms", "Refactoring" )); System.out.println("Sorting List of String by length in JDK 7 ===== color: #3b5bb5;">System.out.println("The original list without sorting"); System.out.println(books); ComparatorString> byLength = new ComparatorString>()< @Override public int compare(String s1, String s2) < return s1.length() - s2.length(); > >; Collections.sort(books, byLength); System.out.println("The same list after sorting string by length"); System.out.println(books); > > Output Sorting List of String by length in JDK 7 ====== The original list without sorting [Effective Java, Algorithms, Refactoring] The same list after sorting string by length [Algorithms, Refactoring, Effective Java]
That’s all about how to compare String by their length and how you can sort a list of String by their length in Java 7 and Java 8. You can see it as a lot more convenient in Java 8 as you can create a custom Comparator in just one line by using the lambda expression.
The JDK 8 API is full of such methods to facilitate even more complex comparison like by using the thenComparing() method you can chain multiple comparators. See these Java 8 and Functional Programming books for more illustrated examples of Comparator in Java 8.
- 10 Example of Lambda Expression in Java 8 (see here)
- How to do Map Reduce in Java 8? (example)
- 10 Example of forEach() method in Java 8 (example)
- How to parse String to LocalDate in Java 8? (program)
- 10 Example of Joining String in Java 8 (see here)
- How to use the filter() with collections in Java 8? (example)
- 10 Example of Stream API in Java 8 (see here)
- 5 Books to Learn Java 8 and Functional Programming (list)
- 5 Free Courses to learn Java 8 and 9 (courses)
- How to implement Comparator in Java 8? (tutorial)
- How to use peek() method of Stream in Java 8? (example)
- How to use String.join() method in Java 8? (tutorial)
- 10 Example of converting a List to Map in Java 8 (example)
- 20 Example of LocalDate and LocalTime in Java 8 (see here)
- How to use Stream.flatMap in Java 8(example)
- Difference between map() and flatMap() in Java 8? (answer)
- How to use Stream.map() in Java 8 (example)
Thanks for reading this article so far. If you liked this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.
P. S.: If you just want to learn more about new features in Java 8 then please see these Java 8 to Java 13 courses It contains short courses that explain all the important features of Java 8 like lambda expressions, streams, functional interfaces, Optional, new Date Time API and other miscellaneous changes.
Как сравнить String по их длине в Java 7 и Java 8?
Привычным способом Java сравнения строк является лексикографический способ, реализованный в методе compareTo() класса String . Но иногда нужно сравнить строки по их длине. По умолчанию нельзя использовать для этого метод compareTo() . Вместо этого нужно написать собственный метод, который вычисляет длину строк с помощью метода length() и сравнивает их. Такой метод должен возвращать положительное значение, если первая String имеет длину больше второй; отрицательное значение, если длина первой String меньше длины второй и ноль, если обе String имеют одинаковую длину.
Можно определить такой одноразовый метод, используя анонимный внутренний класс, и далее использовать его для сортировки списка строк по длине. Это метод хорошо работает в Java 6 и 7 , но в Java 8 он работает еще лучше из-за меньшего количества помех благодаря новой функции, называемой лямбда-выражения.
Вот как можно сделать это в более ранних версиях Java :
public int compare(String s1, String s2)
Сравнение длины строк arraylist в Java 8 можно сделать еще проще, используя лямбда-выражение и новые методы по умолчанию, добавленные в класс java.util.Comparator :
Comparator strlenComp = (a, b) -> Integer.compare(a.length(), b.length());
a и b — это два объекта String. Integer.compare() — это новый метод, добавленный в Java 8 . Поскольку мы используем компаратор для строк, компилятор в состоянии выводить типы a и b , которые являются String .
Как отсортировать список строк по их длине в Java 7 и 8
Ниже приведен пример использования этого компаратора длины строк для сортировки списка строк по их длине. В этом примере мы продемонстрировали программы на JDK 6 и 7 с использованием анонимного класса, и новый способ с использованием лямбда-выражений, который доступен в Java 8 . Он занимает всего одну строку и его намного проще понять, если вы знакомы с синтаксисом лямбда-выражений.
Как отсортировать список строк по их длине в Java 7 и 8
Import java.util.ArrayList; Import java.util.Arrays; Import java.util.Collections; Import java.util.Comparator; Import java.util.List; / * * Программа Java для сортировки списка строк по их длине * / public class StringComparisonByLength < Public static void main (String [] args) < Listbooks = new ArrayList<>(Arrays.asList("Effective Java", "Algorithms", "Refactoring" )); System.out.println("Sorting List of String by length in JDK 7 ======"); System.out.println("The original list without sorting"); System.out.println(books); Comparator byLength = new Comparator() < @Override Public int compare (String s1, String s2) < Return s1.length () - s2.length (); >>; Collections.sort(books, byLength); System.out.println("The same list after sorting string by length"); System.out.println(books); > >
Sorting List of String by length in JDK 7 ====== The original list without sorting [Effective Java, Algorithms, Refactoring] The same list after sorting string by length [Algorithms, Refactoring, Effective Java]
Import java.util.ArrayList; Import java.util.Arrays; Import java.util.Comparator; Import java.util.List; / * * Программа Java для сортировки списка строк по их длине в JDK 8 * / public class SortingListOfStringByLength < public static void main(String[] args) < // В Java 8 System.out.println("Sorting List of String by length in Java 8 ======"); Listcities = new ArrayList<>(Arrays.asList("London", "Tokyo", "NewYork")); System.out.println("The original list without sorting"); System.out.println(cities); cities.sort((first, second) -> Integer.compare(first.length(), second.length())); System.out.println("The same list after sorting string by length"); System.out.println(cities); > >
Sorting List of String by length in Java 8 ====== The original list without sorting [London, Tokyo, NewYork] The same list after sorting string by length [Tokyo, London, NewYork]
Это все, что касается сравнения длины строк Java и сортировки списка String по длине в Java 7 и Java 8 . В последней версии языка делать это намного удобнее, поскольку можно создать пользовательский компаратор только одной строкой, используя лямбда-выражение. API JDK 8 содержит множество подобных методов, которые облегчают еще более сложные сравнения. Например, используя метод thenComparing() , можно связать несколько компараторов.
Вадим Дворников автор-переводчик статьи « How to compare String by their length in Java 7 and 8 »
Пожалуйста, опубликуйте свои отзывы по текущей теме статьи. За комментарии, лайки, дизлайки, подписки, отклики огромное вам спасибо!