Sort words in 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)

    Источник

    How to Sort String in Java Alphabetically

    Scientech Easy

    Sorting string in Java is a common task in programming. For example, we may need to sort a list of items sold by online store, or a list of customer names and email addresses.

    Sorting is an algorithmic technique to put all strings in certain alphabetical order or natural order. It is very helpful for solving real-world problems.

    String class in Java doesn’t provide any method that directly sorts a list of strings. There are two methods with which we can sort string in Java alphabetically:

    Using User defined Logic

    We will sort a string array by comparing each element with other elements. Let’s take an example program in which we will take a group of elements into an array and sort them into ascending order.

    We will use swapping technique in which we will compare the first of the array with the immediate element. If it is bigger than immediate element, then they are swapped (interchanged).

    Since we are sorting in ascending order, we expect the smaller elements to be in the first place. When two elements are swapped or interchanged, the number of elements to be sorted becomes lesser by 1. Let’s write the complete code for it.

    Program code 1:

    package stringPrograms; import java.util.Arrays; public class SortingString < public static void main(String[] args) < // Creating an array of String. String[] countries = ; int size = countries.length; // User defined logic to sort string array. // Applying nested for loop. for(int i = 0; i < size - 1; i++) < for (int j = i+1; j < countries.length; j++) < // Comparing each element of the array with the rest elements. if(countries[i].compareTo(countries[j])>0) < // Swapping array elements String temp = countries[i]; countries[i] = countries[j]; countries[j] = temp; >> > // Displaying the sorted array in alphabetical order. System.out.println(Arrays.toString(countries)); > >
    Output: [ Australia, Denmark, France, Germany, India, Italy, South-Africa, USA]

    Using Arrays.sort() Method

    In Java, Arrays class defined in the java.util package provides a static method named sort() to sort an array in ascending order. It uses an algorithm named Dual-Pivot Quicksort for sorting.

    Its complexity is O(n log(n)). Since it is a static method that parses an array as a parameter and returns nothing. We can directly call it by using the class name.

    It accepts an array of primitive types, such as int, float, double, long, char, byte. The general syntax of using this method is:

    public static void sort(int[] a)

    Where a is an array to be short.

    Note : Like Arrays class, Java Collections class also provides a sort() method to sort the array. But there is a difference between them.

    The sort() method of Arrays class is applicable for primitive type while the sort() method of the Collections class is applicable for objects Collections, such as ArrayList, LinkedList, etc.

    We can perform sorting of an array in the following ways:

    • Ascending Order or Alphabetical Order or Natural Order
    • Descending Order or Reverse Natural Order

    How to Sort String in Java Alphabetically or Ascending Order

    Alphabetical order is a natural order or ascending order in which elements arrange in the lowest to highest. Let’s create a Java program in which we will sort string array using the sort() method of the Arrays class.

    Program code 2:

    package stringPrograms; import java.util.Arrays; public class AscOrder < public static void main(String[] args) < // Creating an array of String. String[] fruits = ; // Sorting string array in alphabetical order or ascending order Arrays.sort(fruits); // Displays the sorted string array in ascending order. System.out.println("Sorting elements in alphabetical order: "); System.out.println(Arrays.toString(fruits)); > >
    Output: Sorting elements in alphabetical order: [Apple, Banana, Guava, Mango, Orange, Papaya]

    Sorting String Array in Descending Order or Reverse Natural Order

    Java Collections class provides a static method named reverseOrder() to sort the array in reverse-lexicographic order. Since it is a static method, so we can call it directly by using the class name.

    The reverseOrder() method does not accept any parameter. It returns a comparator that reverse elements in the natural ordering (ascending order).

    It means that the sort() method sorts array elements in the ascending order, after that reverseOrder() method reverses the natural ordering. Thus, we get the sorted array elements in descending order.

    The general syntax of using reverseOrder() method is as:

    public static Comparator reverseOrder()

    Suppose x[ ] is an array of elements to be sorted in the descending order. We will use reverseOrder() method of Collections class in the following ways:

    Arrays.sort(x, Collections.reverseOrder());

    Let’s take an example program in which we will sort a string array in the descending order.

    Program code 3:

    package stringPrograms; import java.util.Arrays; import java.util.Collections; public class DescOrder < public static void main(String[] args) < // Creating an array of String. String[] cities = ; // Sorting string array in descending order. Arrays.sort(cities, Collections.reverseOrder()); // Displays the sorted string array in descending order. System.out.println("Sorted string array in descending order: ") System.out.println(Arrays.toString(cities)); > >
    Output: Sorted string array in descending order: [Sydney, Paris, New York, Moscow, Dhanbad, Cape town]

    In this tutorial, you learned how to sort string elements in ascending or descending order alphabetically. Hope that you will have understood the basic methods of sorting string alphabetically.

    In the next tutorial, we will learn anagram in Java and how to check it.
    Thanks for reading.
    ⇐ PrevNext ⇒

    Источник

    Читайте также:  Get java home variable
Оцените статью