1. Use a TreeMap to sort the Words that are to be displayed, as usual, in the ri
ID: 3836518 • Letter: 1
Question
1. Use a TreeMap to sort the Words that are to be displayed, as usual, in the right column of the GridLayout. All the code you need is in the PowerPoint on TreeMaps. You will need to create a Comparator for the class Word. 2. Use a Regular Expression to verify that the passed to the constructor of a Word is three letters. The format of the input file will be the same as Project 1. Submitting the Project. You should now have at least the following files to submit for this project: Project 4 java Word java Word GUI. java WordNode java. Word List .java Un sortedWordList java SortedWordList ava FileMenuHandler java Word Comparator.java Illegal java Submit a jar file Create a jar file called Project4Jar and submit and upload it to Blackboard by the due date for full credit.Explanation / Answer
import java.util.Map;
import java.util.TreeMap;
/**
*
* @author Sam
*/
public class SortedWordList {
TreeMap<String, Integer> words;
int count;
public SortedWordList() {
words = new TreeMap<>();
count = 0;
}
private boolean verify(String word){ //this method will be called by the constructor of word class
return word.matches("[a-zA-Z][a-zA-Z][a-zA-Z]");
}
public void insert(String word) {
count ++; //increase count
if (words.containsKey(word)) { //if word was already added
int c = words.get(word); //get individual count
c ++; //increase the count
words.replace(word, c); //and update count
}
else // if not present
words.put(word, 1); //add word as well as count value as 1
}
public String[] getSortedArray() {
String[] arr = new String[count]; //create array
int pos = 0;
while (!words.isEmpty()) { //check if the collection is empty
Map.Entry<String, Integer> entry = words.pollFirstEntry(); //remove the first entry
for (int i = 0; i < entry.getValue(); i++) //add it to the array
arr[pos++] = entry.getKey();
}
//we should now re populate the treemap
count = 0; //reset count since the map is empty
for (String w : arr)
insert(w); //add every words into the tree
return arr;
}
}
This is the most simple class i can think of. If you need the class to be more customized, please comment below, I shall try my best to resolve all your queries.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.