Java TreeSets -You MUST use java.util.TreeSet. -Build a set of unique Strings -I
ID: 3682586 • Letter: J
Question
Java TreeSets
-You MUST use java.util.TreeSet.
-Build a set of unique Strings
-Iterate over the contents of the set.
-Print the values in ascending length order.
-If 2 or more strings are the same length, print them in REVERSE lexicographical order.
- you will need to pass a custom Comparator instance to your TreeSet constructor.
-Make sure to implement this using an inner class, such that the entirety of Program 1 is in a single java file.
-You can choose any String values
-Program does not have to be interactive.
-Make sure to show what happens when duplicate strings and multiple strings with the same lengths are included.
Here is an example of what your program should do:
public static void main(String[] args)
{
TreeSet<String> tester = new TreeSet<>(new LenComp());
tester.add("alpha");
tester.add("b");
tester.add("i");
tester.add("sample");
tester.add("a");
tester.add("slack");
for (String s : tester)
{
System.out.println(s);
}
}
output:
i
b
a
slack
alpha
sample
Explanation / Answer
import java.util.Comparator;
import java.util.TreeSet;
public class StringSorting {
// defining my comparator
static class LenComp implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
if (o1.length() < o2.length())
return -1;
else if (o1.length() > o2.length())
return 1;
else
return o2.compareTo(o1);
}
}
public static void main(String[] args) {
TreeSet<String> tester = new TreeSet<>(new LenComp());
tester.add("alpha");
tester.add("b");
tester.add("i");
tester.add("sample");
tester.add("a");
tester.add("slack");
for (String s : tester) {
System.out.println(s);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.