Sunday, 7 September 2014

Sorting Example for a Collection or Array of strings

          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




To know FAQ's in Interviews on Selenium Please ClickHere
To know more on SQL Queries Required For Testers Please  ClickHere

No comments:

Post a Comment