You should just define a custom Comparator for Strings and pass that in as the Comparator when you build the TreeSet. Here's a similar StackOverflow question with a detailed answer:
TreeSet Custom Comparator Algo .. String Comparision
You haven't specified exactly what you're doing with the asterisk, but below is an example that sorts based on if the string contains an asterisk. Note that I use a List<String>
here instead of a HashMap
. The fact that you're getting the values from a HashMap
isn't actually important—you'd do the same thing for any Java Collection
.
List<String> strs = Arrays.asList("a","b","c","a*","b*");
Comparator<String> starCompare = new Comparator<String>() {
@Override public int compare(String a, String b) {
int aStar = a.contains("*") ? 1 : 0;
int bStar = b.contains("*") ? 1 : 0;
return (aStar != bStar)
? Integer.compare(aStar, bStar)
: a.compareTo(b);
}
};
// Without comparator
SortedSet<String> set1 = new TreeSet<String>(strs);
System.out.println(set1); // => [a, a*, b, b*, c]
// With comparator
SortedSet<String> set2 = new TreeSet<String>(starCompare);
set2.addAll(strs);
System.out.println(set2); // => [a, b, c, a*, b*]
Notice how for the output of set2
, which uses the custom Comparator
, the entries including an *
are last in the sorted set.