Sorting a Strings in Java

Java 8Object Oriented ProgrammingProgramming

In order to sort a string in java we could use the arrays API and its inbuilt method sort which internally implementing sorting algorithm and would return a sorted string.

First we will convert our string into a character array and then sort this array using sort method of Arrays class in Java now we have sorted array from which we would construct a new string using sorted array as its parameter in constructor.

Example

 Live Demo

import java.util.Arrays;
public class StringSort {
   public static void main(String[] args) {
      String str ="fghryisnskfg";
      char[] arr = str.toCharArray();
      Arrays.sort(arr);
      String str1 = new String(arr);
      System.out.println(str1);
   }
}

Output

myCSV.csv file created with following text −

ffgghiknrssy
raja
Published on 04-Dec-2018 07:29:00
Advertisements