Ask Your Question
4

How can the string be sorted in Java?

asked 2022-02-16 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-11-18 02:00:00 +0000

plato gravatar image

In Java, the String class implements the Comparable interface, which means that String objects can be sorted using the compareTo method. The compareTo method compares two strings lexicographically, which means that it compares the corresponding characters of each string from left to right.

For example, the following code sorts an array of Strings in ascending order:

String[] fruits = {"banana", "apple", "pineapple", "kiwi"};
Arrays.sort(fruits);

This will result in the fruits array being sorted in alphabetical order: {"apple", "banana", "kiwi", "pineapple"}.

Alternatively, you can use the Comparator interface to define your own sorting logic. For example, the following code sorts an array of Strings by length:

String[] fruits = {"banana", "apple", "pineapple", "kiwi"};
Arrays.sort(fruits, Comparator.comparing(String::length));

This will result in the fruits array being sorted by length: {"kiwi", "apple", "banana", "pineapple"}.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-16 11:00:00 +0000

Seen: 5 times

Last updated: Nov 18 '21