Search code examples
javahashmapsortedset

Sorting a Hashmap's values with sorted Set


I have a hashmap with values that both contain and do not contain asterisks (* ). I want to sort my values so that all values with an (* ) come last. I tried using this line of code:

    SortedSet<String> orderedValues = new TreeSet<String>(myHashMap.values());

but it orders it alphabetically then withing that places all values with an (*) first. is there anyway to reverse that???


Solution

  • you have to write your own java.util.Comparator to do customized sorting. Default String sorting is alphabetical.

    EDITED to meet new requirements to group sorting by no asterisks, then all with 1 then all with 2 etc

    If you want to group sorting by no asterisks, then all with 1 then all with 2 etc and then inside each grouping, sort alphabetically, then you probably want something like this:

    public class AsterisksLast implements Comparator<String>{
    
    @Override
    public int compare(String o1, String o2) {
    
    
        int numAsterisksInO1 = numberOfAsterisksIn(o1);
        int numAsterisksInO2 = numberOfAsterisksIn(o2);
    
        if(numAsterisksInO1 == numAsterisksInO2){
            //both contain same number of asterisks
            //(which may be 0)
            //sort 
            //alphabetically
            return o1.compareTo(o2);
        }
        //different number of asterisks sort by fewest
        return Integer.compare(numAsterisksInO1, numAsterisksInO2);
    
    }
    
    private int numberOfAsterisksIn(String s){
        char[] chars =s.toCharArray();
        int count=0;
        for(int i=0; i<chars.length; i++){
            if(chars[i] == '*'){
                count++;
            }
        }
        return count;
    }
    

    }

    then you need to give it to your TreeSet

    SortedSet<String> orderedValues = new TreeSet<String>(new AsterisksLast());
    orderedValues.addAll(myHashMap.values());