A list of strings to be sorted by using the array and by using Array list. To describe it a small piece of code is required.
Example:
package Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class StringSortExample {
public static void main(String[] args) throws Exception {
String[] strArray = { "Abhishek", "selenium", "Automation" };
//displaying the string array
displayArray(strArray);
///To sort an array
Arrays.sort(strArray);
//after sorting displaying array
displayArray(strArray);
//sorted array with case insensitive
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
displayArray(strArray);
System.out.println("---------------");
///sorting strings using arraylist
List<String> strList = new ArrayList<String>();
strList.add("Abhishek");
strList.add("Webdriver");
strList.add("Automation");
displayList(strList);
Collections.sort(strList);
displayList(strList);
Collections.sort(strList, String.CASE_INSENSITIVE_ORDER);
displayList(strList);
}
public static void displayArray(String[] array) {
for (String str : array) {
System.out.print(str + " ");
}
System.out.println();
}
public static void displayList(List<String> list) {
for (String str : list) {
System.out.print(str + " ");
}
System.out.println();
}
}
Output:
Abhishek selenium Automation
Abhishek Automation selenium
Abhishek Automation selenium
---------------
Abhishek Webdriver Automation
Abhishek Automation Webdriver
Abhishek Automation Webdriver
Example:
package Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class StringSortExample {
public static void main(String[] args) throws Exception {
String[] strArray = { "Abhishek", "selenium", "Automation" };
//displaying the string array
displayArray(strArray);
///To sort an array
Arrays.sort(strArray);
//after sorting displaying array
displayArray(strArray);
//sorted array with case insensitive
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
displayArray(strArray);
System.out.println("---------------");
///sorting strings using arraylist
List<String> strList = new ArrayList<String>();
strList.add("Abhishek");
strList.add("Webdriver");
strList.add("Automation");
displayList(strList);
Collections.sort(strList);
displayList(strList);
Collections.sort(strList, String.CASE_INSENSITIVE_ORDER);
displayList(strList);
}
public static void displayArray(String[] array) {
for (String str : array) {
System.out.print(str + " ");
}
System.out.println();
}
public static void displayList(List<String> list) {
for (String str : list) {
System.out.print(str + " ");
}
System.out.println();
}
}
Output:
Abhishek selenium Automation
Abhishek Automation selenium
Abhishek Automation selenium
---------------
Abhishek Webdriver Automation
Abhishek Automation Webdriver
Abhishek Automation Webdriver
No comments:
Post a Comment