In: Computer Science
You are provided with an array of Strings and a list of Strings. Sort the elements (1) in natural order, (2) in reverse natural order and (3) by the length of each String. You can fill in the details by using the following stub file:
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Midterm01 { public static void main(String[] args) { String[] arrayOfCities = { "Atlanta", "Savannah", "New York", "Dallas", "Rio" }; List<String> listOfCities = Arrays.asList("Atlanta", "Savannah", "New York", "Dallas", "Rio"); System.out.print("\nSorting a String array in natural order..."); // your work here System.out.print("\nSorting a String array in reverse natural order..."); // your work here System.out.print("\nSorting a String array by length of the Strings..."); // your work here System.out.print("\nSorting a String list in natural order..."); // your work here System.out.print("\nSorting a String list in reverse natural order..."); // your work here System.out.print("\nSorting a String list by length of Strings..."); // your work here } }
This is the code
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
public class ProgrammingProblem1{
public static void main(String[] args) {
String[] arrayOfCities = { "Atlanta", "Savannah", "New York", "Dallas", "Rio" };
List<String> listOfCities = Arrays.asList("Atlanta", "Savannah", "New York", "Dallas", "Rio");
System.out.print("\nSorting a String array in natural order...");
// your work here
Arrays.sort(arrayOfCities);
System.out.println(Arrays.toString(arrayOfCities));
System.out.print("\nSorting a String array in reverse natural order...");
// your work here
Arrays.sort(arrayOfCities, Collections.reverseOrder());
System.out.println(Arrays.toString(arrayOfCities));
System.out.print("\nSorting a String array by length of the Strings...");
// your work here
Arrays.sort(arrayOfCities, (s1, s2)->Integer.compare(s1.length(), s2.length()));
System.out.println(Arrays.toString(arrayOfCities));
System.out.print("\nSorting a String list in natural order...");
// your work here
Collections.sort(listOfCities);
System.out.println(listOfCities);
System.out.print("\nSorting a String list in reverse natural order...");
// your work here
Collections.sort(listOfCities, Collections.reverseOrder());
System.out.println(listOfCities);
System.out.print("\nSorting a String list by length of Strings...");
// your work here
Collections.sort(listOfCities, (s1, s2)->Integer.compare(s1.length(), s2.length()));
System.out.println(listOfCities);
}
}
And this is the output that i got
Hope this will be helpful