2 The Arrays class contains various methods for manipulating arrays (such as sor
ID: 3915824 • Letter: 2
Question
2 The Arrays class contains various methods for manipulating arrays (such as sorting and searching). Research this in the Java API via a web browser. Use the methods of this class to sort an array of strings in decreasing order by string length. Thus, "stelliferous* would come somewhere before 'cat* because 'stelliferous is longer than 'cat" Additionally, strings of the same length must be sorted lexicographically (alphabetic order),. but in descending order (that is, 'zanzibar" would come before 'generous"). Hint: Look in the API for a sort method that lets you supply a Comparator We have already seen the Comparable interface, but not Comparator. A class that implements Comparable has a compare To method that compare myself to another object ts the Comparator interface has a compare In this case, though, a class that impemen method that compares two other objects (the implementing class is not one of them). It must be capable of judging the relative order of those two objects according to the nules Note that the strings should be loaded Use the Java API documentation to help with this. from the provided sample file wordlist.txt.Explanation / Answer
Using a comparator and using compareTo method I am first sorting the strings in ascending order ,then we can take the output in a reverse way also this handles the reverse lexicographical order as well when strings are of same length. Here is the source code -
package sortstrings;
import java.util.*;
import java.io.*;
public class Sortstrings {
public static void sortStringsDesc(String str[]){
Arrays.sort(str, new java.util.Comparator<String>() {
@Override
public int compare(String s1, String s2) {
if (s1.length() == s2.length())
{
return s1.compareTo(s2);
}
return s1.length() - s2.length();// comparision
}
});
for(int i=str.length - 1;i >= 0;i--)
System.out.print(str[i]+" ");
}
public static void main(String args[]) throws IOException {
FileReader fileReader = new FileReader("wordlist.txt"); // I included the file in the project folder itself.
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
lines.add(line);
}
bufferedReader.close();
String[] arr = lines.toArray(new String[lines.size()]);
sortStringsDesc(arr);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.