Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Sort a list of words by length, then by alphabetical order

Tags:

java

sorting

map

I am told to have a list of words sorted by length, and those that have the same length are sorted by alphabetical order. This is what I have for the method that does that so far.

public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
    TreeMap<String, Integer> s = new TreeMap<String, Integer>();
    ArrayList<Integer> count = new ArrayList<Integer>();
    String line;        
    int length;
    while ((line = r.readLine()) != null) {
        length = line.length();

        s.put(line, length);
        if (!count.contains(length)){
            count.add(length);
        }
    }    
    Collections.sort(count);
    System.out.println(count);
}

My mindset was to use a TreeMap to keep the String, and the length of the word as the key. I also have an ArrayList that keeps track of all the word's lengths without any duplicates, it's then sorted.

I was hoping to somehow call on the TreeMap for the key value of 5, which would list all the words with 5 letters in it.

I was wondering if I'm on the right track? I've been playing around for over an hour and can't seem to figure out what I should do after this. Am I approaching this from the right angle?

like image 436
user1692517 Avatar asked Dec 12 '22 11:12

user1692517


1 Answers

you want to use a string comparator that compares by length 1st. like so:

public class LengthFirstComparator implements Comparator<String> {
    @Override
    public int compare(String o1, String o2) {             
        if (o1.length()!=o2.length()) {
            return o1.length()-o2.length(); //overflow impossible since lengths are non-negative
        }
        return o1.compareTo(o2);
    }
}

then you could simply sort your Strings by calling Collections.sort(yourStringList, new LengthFirstComparator());

like image 97
radai Avatar answered Mar 30 '23 01:03

radai