IN JAVA Given an array of strings, use the java.util.Collections.sort(list, comp
ID: 3831653 • Letter: I
Question
IN JAVA
Given an array of strings, use the java.util.Collections.sort(list, comparator) method to sort the strings in an increasing order of string length.
String[] list = {"red", "blue", "yellow"};
a. Define your comparator class.
b.Write the code that uses the comparator class to sort the array list.
public class Sort {
public static void main(String[] args) {
String[] list = {"red", "blue", "yellow"};
// Write your code to sort using sort(list, comparator)
// Write the code to display all strings in order
// and in uppercase cases
}}
Explanation / Answer
Sort.java
import java.util.ArrayList;
public class Sort {
public static void main(String[] args) {
//String[] list = {"red", "blue", "yellow"};
ArrayList<String> list = new ArrayList<String>();
list.add("red");
list.add("blue");
list.add("yellow");
// Write your code to sort using sort(list, comparator)
StringComparator comparator = new StringComparator();
java.util.Collections.sort(list, comparator) ;
// Write the code to display all strings in order
// and in uppercase cases
for(String s:list){
System.out.println(s.toUpperCase());
}
}}
StringComparator.java
import java.util.Comparator;
public class StringComparator implements Comparator<String> {
public int compare(String a, String b) {
return a.compareTo(b);
}
}
Output:
BLUE
RED
YELLOW