Java:按长度排序一个单词列表,然后按字母顺序排列 [英] Java: Sort a list of words by length, then by alphabetical order
问题描述
public static void doIt(BufferedReader r,PrintWriter w)throws IOException {
TreeMap< String,Integer> s = new TreeMap< String,Integer>();
ArrayList< Integer> count = new ArrayList< Integer>();
字符串;
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);
}
我的心态是使用TreeMap来保留String,这个词作为关键。我还有一个ArrayList,跟踪所有的单词的长度,没有任何重复,然后排序。
我希望以某种方式调用TreeMap的关键值5,它会列出所有有5个字母的单词。
我想知道我是否在正确的轨道上?我已经玩了一个多小时,似乎无法弄清楚我应该做什么。我从正确的角度来看这个吗?
最简单的方法是写一个 Comparator&串GT;
。 比较器< String>
将收到两个单词,并进行比较。如果第一个比第二个更短,它应该返回-1。如果第二个比第一个更短,它将返回1.如果它们的长度相同,它应该调用默认的 String
compareTo
方法。然后,您可以使用此自定义的比较器
来简单地排序列表。
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?
The easiest way would be to write a Comparator<String>
. The Comparator<String>
would receive two words, and compare them. If the first was shorter than the second, it should return -1. If the second was shorter than the first, it would return 1. If they are the same length, it should call the default String
compareTo
method. You can then simply sort your list using this custom Comparator
.
这篇关于Java:按长度排序一个单词列表,然后按字母顺序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!