Sorting strings with java

Сортировка списка строк в Java

В этом посте мы обсудим, как отсортировать список строк в лексикографическом порядке в Java.

1. Использование Collections.sort() метод

Простое решение для на месте отсортировать список строк в лексикографическом порядке с помощью Collections.sort() метод. Он принимает изменяемый список, размер которого не обязательно должен изменяться.

результат:

[Amazon, Apple, Facebook, Google, Netflix]

The Collections.sort() метод необязательно принимает компаратор, чтобы обеспечить точный контроль над порядком сортировки. Чтобы сделать сравнение между двумя строками нечувствительными к регистру, вы можете использовать String.CASE_INSENSITIVE_ORDER comparator.

результат:

[Amazon, APPLE, Facebook, GOOGLE, Netflix]

2. Использование List.sort() метод

Другой альтернативой сортировке списка строк на месте является метод List.sort() метод, добавленный в спецификацию JDK 1.8. Collections.sort() метод представляет собой оболочку над List.sort() метод. Следовательно, приведенный выше код эквивалентен:

результат:

[Amazon, Apple, Facebook, Google, Netflix]

Вы можете использовать String.CASE_INSENSITIVE_ORDER компаратор, чтобы операция сортировки сравнивала строки, игнорируя их порядок.

результат:

[Amazon, APPLE, Facebook, GOOGLE, Netflix]

3. Использование Stream.sorted() метод

Чтобы создать отсортированную копию списка, вы можете использовать Java 8 Stream. Идея состоит в том, чтобы создать последовательный поток по элементам в списке, отсортировать поток с помощью sorted() и соберите все отсортированные элементы в новый список. Это показано ниже:

Источник

Sort a String in Java

Java Course - Mastering the Fundamentals

Strings are nothing but a sequence of characters. In certain situations, we need to reorder this sequence in such a way that its characters are arranged in lexicographically increasing or decreasing order. This is where the concept of sorting a string comes in.

Java has several ways to rearrange the characters inside the string in a particular order, many of them require it to be converted into an array of characters, like the Arrays.sort() and sorted() methods. Java has inbuilt methods to sort a string in any order be it increasing or decreasing.

Introduction

A string is a collection of characters that can include letters, numbers, symbols, and even spaces. To be recognized as a string in Java, it must be surrounded by double-quotes. For example, «Scaler» , «how to sort a string in java?» and «123Random» are strings.

Strings in Java can be created using two ways.

To get the desired output from our program, we frequently need to arrange the individual characters in strings in different orders. Sorting is the process of arranging a sequence (string in this case) based on desired criteria.

In other words, sorting a string is the procedure to arrange its characters in increasing or decreasing order. Java provides methods like Arrays.sort() , reverseOrder() and sorted() to sort a string, which are covered in the subsequent sections.

Method 1: Arrays.sort() Method

In Java, the Arrays.sort() method is used to sort any type of array, whether it is an integer or a character array. To sort a String using this method:

  • Convert the input string into a char array using the toCharArray() method.
  • Sort the char array using Arrays.sort() method.
  • Finally convert the sorted array back to a String.

This Arrays.sort() method has the time complexity of O ( N l o g N ) O(NlogN) O ( N l o g N ) where N is the size of the array.

Custom sorting using Arrays.sort() method

Custom sorting allows us to modify the Arrays.sort() method’s sorting criteria since we know that sorting is done based on ASCII values of characters therefore we can define a custom logic to compare two characters and decide which one should come first.

The demonstration for the same is shown below, where we will be sorting the string «scaler» in reverse order.

  • Convert the input string into a Character array by creating a Character array of length equal to the size of the string. Populate this array with the characters of the string using a for loop.
  • Pass one more parameter to the Arrays.sort() method that is the Comparator and override the default comparison criteria based on ASCII values.
  • Syntax of the compare() function to be used as Comparator:
  • The compare() function returns a negative value if o1 has to come first, positive if o2 has to come first, and 0 if they are the same.

Method 2: Using Java 8 Streams and sorted() Method

Java 8 provides us with the Stream , which can sort any kind of list using its built-in sorted() method. So we will need to convert the string into a list of characters using the chars() method first then sort it using the sorted() method.

Explanation:

  • The example above sorts the String «Scaler» in alphabetically increasing order.
  • The inputstr is converted into the list of chars and then, this list is arranged in increasing alphabetical order using the sorted() method.
  • The collect() method takes the sorted object and passes it to appendCodepoint() method of [StringBuilder](https://www.scaler.com/topics/java/stringbuilder-in-java/) , which appends the string representation of each codepoint object to the sequence.
  • Finally toString() method is used to convert it into a string.

Method 3: reverseOrder() Method

The reverseOrder() method of the Java Collections class is used to sort an array in lexicographically decreasing order. Because it is a static method, we can use the class name to call it directly.

  • Convert the input string into a Character array similar to what we have done above.
  • Pass a second argument to Arrays.sort() method as Collections.reverseOrder() which reverses the ordering of characters after sorting.
  • The array is first sorted in ascending order using the Arrays.sort() method, and then the natural ordering is reversed using the reverseOrder() method, resulting in a sorted array in descending order.

The syntax for reverseOrder() :

Explanation:

  • We have used the input string «scaler» string to demonstrate reverseOrder() method.
  • First, we have converted the string into a Character array and then use the Arrays.sort() method passing reverseOrder() as a comparator to rearrange it.
  • Convert it back to a String by applying toString() method on StringBuilder object sb .

Time Complexity: O ( n ∗ l o g n ) O(n*log n) O ( n ∗ l o g n ) where n n n is the number of characters in the input string.

Conclusion

  • Strings are a sequence of characters which can be rearranged in a particular order such as lexicographically increasing or decreasing order.
  • Strings in Java can be sorted using various methods such as:
    • Arrays.sort()
    • sorted() method (Java 8 Streams)

    Источник

    Sort String in Java

    Sort String in Java

    Sorting a string in Java is something which is not in-built Java feature in which direct method is available within Java library to sort string though Java does provide techniques to sort array of elements by using Arrays.sort. Using few different methods which are provided by Java library we can sort in Java easily and sorting a string has various different uses cases in any Java application.

    Web development, programming languages, Software testing & others

    How to Sort String in Java Using Various Ways?

    It has 2 major techniques which can be used by developer depending on the use case.

    • Technique 1: Using Array.sort().
    • Technique 2: Using custom comparator to sort the string in Java.
    • Technique 3: Using Java 8 streams features along with Strings.chars.

    1. Technique 1 – Using Array.sort()

    This is a very simple and straight forward technique. The way we sort array of element in Java similar way we and similar logic will be applied.

    To implement this technique below are the steps and an example to this sorting:

    • Step 1: Get the input String from the user and convert the input String to Array of Characters using Arrays.toCharArray() method which is present in java.util.Arrays
    • Step 2: Apply natural sorting to this newly created array of characters using Arrays.sort method which is also present in same jar java.util.Arrays.
    • Step 3: Convert this sorted array of characters back to string using Java string class and store the newly created string in string object as strings are immutable
    import java.util.Arrays; import java.util.Scanner; public class SortString < public static void main(String args[]) < Scanner scanner = new Scanner(System.in); System.out.println("Input String Value which should be sorted : "); String inputString = scanner.nextLine(); char arrayOfCharacters[] = inputString.toCharArray(); // Step 1 Arrays.sort(arrayOfCharacters); // Step 2 String sortedString = new String(arrayOfCharacters); // Step 3 System.out.println("Before Sorting : " + inputString); System.out.println("After Sorting : " + sortedString); >>

    Sort String in Java op 2

    Limitations:

    • It is ideally done by Java framework using the ASCII value of each character which is present in the string.
    • As a result this technique should be used only incase the string sorting which is required is case sensitive which means as the ASCII value of upper case characters is less than lower case characters then sorting would not be proper in case your string has both case characters i.e mixed String.

    Sort String in Java 4

    2. Technique 2 – Using custom comparator

    This technique is used mainly when the input String can be of mixed characters with lowercase as well as upper case. This is not a straight forward technique as above and requires some bit of more coding. We will be using the same array sorting technique provided by Java but along with that we will use comparator which will help us compare each characters in the string.

    To implement this technique below are the steps and an example to this type of string sorting in Java.

    • Step 1: Get the input string from the user and convert the input string to array of characters using Java for loop feature.
    • Step 2: Apply Java sorting to this newly created array of characters using Arrays.sort method along with comparator which will ignore casing during sorting and this is present in same jar java.util.Arrays.
    • Step 3: Convert this sorted array of characters back to string using Java StringBuilder class and no need to store the newly created string in string object as StringBuilder is mutable.
    import java.util.Arrays; import java.util.Scanner; import java.util.Comparator; public class SortString < public static void main(String[] args) < Scanner scanner = new Scanner(System.in); System.out.println("Input a String Value which should be sorted : "); String inputString = scanner.nextLine(); Character arrayOfCharacters[] = new Character[inputString.length()]; for (int i = 0; i < inputString.length(); i++) < arrayOfCharacters[i] = inputString.charAt(i); // Step 1 >Arrays.sort(arrayOfCharacters, new Comparator() < // Step 2 @Override public int compare(Character c1, Character c2) < return Character.compare(Character.toLowerCase(c1), Character.toLowerCase(c2)); >>); StringBuilder outputString = new StringBuilder(arrayOfCharacters.length); for (Character c : arrayOfCharacters) outputString.append(c.charValue()); // Step 3 System.out.println("Before Sorting : " + inputString); System.out.println("After Sorting considering casing: " + outputString.toString()); > >

    custom Comparator

    Limitations:

    • This sorting technique is an ideal way of doing sorting in Java where the input string can be any value with upper and lower case characters.
    • There is no as such limitations to this technique of sorting but it is a bit lengthy code to implement.

    3. Technique 3 – Using Java 8 streams features along with Strings.chars method

    This technique is a new technique with minimal line of code and using Java 8 Stream features along with String.chars method which comes inline with Java 8 only. So make sure when you apply this technique your Java application used mainly when the input string can be of mixed characters with lowercase as well as upper case. This is not a straight forward technique as above and requires some bit of more coding. We will be using the same Array sorting technique provided by Java but along with that we will use comparator which will help us compare each characters in the string.

    Conclusion

    Sorting a String in Java is very easy and comes with lot of different approaches and developer can use any of these depending on the requirement of the application. It varies from 2 liner code to writing a whole new method to sort and also allows to sort a string by ignore the case as well.

    This is a guide to Sort String in Java. Here we discuss the introduction and how to sort string in java using various ways? You may also have a look at the following articles to learn more –

    500+ Hours of HD Videos
    15 Learning Paths
    120+ Courses
    Verifiable Certificate of Completion
    Lifetime Access

    1000+ Hours of HD Videos
    43 Learning Paths
    250+ Courses
    Verifiable Certificate of Completion
    Lifetime Access

    1500+ Hour of HD Videos
    80 Learning Paths
    360+ Courses
    Verifiable Certificate of Completion
    Lifetime Access

    3000+ Hours of HD Videos
    149 Learning Paths
    600+ Courses
    Verifiable Certificate of Completion
    Lifetime Access

    All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access

    Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access

    Источник

    Читайте также:  Check null c sharp
Оцените статью