Sorting an Array of string in java
Way 1: Sort String array using CompareTo() method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.util.*; public class Main { public static void main(String []args) { Scanner sc=new Scanner(System.in); System.out.println("Enter no of i/p elements"); int no_of_ele=sc.nextInt(); String str_arr[]=new String[no_of_ele]; for(int i=0;i<no_of_ele;i++) { str_arr[i]=sc.next(); } //compare String temp; for(int i=0;i<str_arr.length;i++) { for(int j=0;j<str_arr.length;j++) { if(str_arr[j].compareTo(str_arr[i])>0) { temp=str_arr[j]; str_arr[j]=str_arr[i]; str_arr[i]=temp; } } } } } |
Way 2: Sort String array using Arrays.sort() method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.*; public class Main { public static void main(String []args){ Scanner sc=new Scanner(System.in); System.out.println("Enter no of i/p elements"); int no_of_ele=sc.nextInt(); String str[]=new String[no_of_ele]; for(int i=0;i<no_of_ele;i++) { str[i]=sc.next(); } Arrays.sort(str); System.out.println(Arrays.toString(str)); } } |
Way 3: Sort String array using Collections.sort() method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.*; public class Main { public static void main(String []args){ Scanner sc=new Scanner(System.in); System.out.println("Enter no of i/p elements"); int no_of_ele=sc.nextInt(); ArrayList arr=new ArrayList(); while(no_of_ele>0) { arr.add(sc.next()); no_of_ele--; } System.out.println(arr); Collections.sort(arr); System.out.println(arr); } } |