Home  >  Article  >  Java  >  How to sort strings in java

How to sort strings in java

下次还敢
下次还敢Original
2024-04-02 02:18:18538browse

How to sort strings in Java: Use the Arrays.sort() method to sort a string array in ascending order. Use the Collections.sort() method to sort a list of strings in ascending order. Use the Comparator interface for custom sorting of strings.

How to sort strings in java

How to sort strings using Java

In Java, sorting strings is a common operate. There are several ways to accomplish this task, here are the two most common and efficient:

Method 1: Arrays.sort()

The Arrays.sort() method can be used to sort an array of strings in place. It uses the merge sort algorithm, which is stable and efficient.

<code class="java">String[] strings = {"Apple", "Orange", "Banana", "Grape"};
Arrays.sort(strings);</code>

The above code sorts the strings in the strings array in ascending order.

Method 2: Collections.sort()

Collections.sort() method can be used to sort a list of strings. It uses either merge sort or quick sort algorithm, depending on the size of the list.

<code class="java">List<String> strings = Arrays.asList("Apple", "Orange", "Banana", "Grape");
Collections.sort(strings);</code>

The above code sorts the strings in the strings list in ascending order.

Custom sorting

If you need to sort strings according to custom rules, you can use the Comparator interface. This interface provides a compare() method that compares two strings according to the desired collation.

<code class="java">Comparator<String> comparator = (s1, s2) -> s1.length() - s2.length();
Collections.sort(strings, comparator);</code>

The above code sorts the strings in the strings list in descending order by string length.

The above is the detailed content of How to sort strings in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn