根据Java中的字符列表对单词列表进行排序 [英] Sorting list of words according to list of characters in Java
本文介绍了根据Java中的字符列表对单词列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有:
List<String> alphabet; (contains 26 unique characters as elements, for example
qwertyuiosapdfghjklzcxvbnm)
List<String> wordsToArrange; contains words as elements, for example:
- apple
- stream
- posthouse
- sea
- seed
我需要根据我写的字母排列单词.
I need to arrange the words according to the alphabet i have made.
我目前的方法是循环.
My approach at the moment is with for cycles.
alphabet(i) compare it with all the words charAt(0)
if only 1 is found i put it to a new list arrangedList
but if 2 is found i go alphabet(i+1) till the letter is found and now i can put them in a right order to arrangedList....
then move back to alphabet(i+1) till alphabet(26) and now all should be arranged correctly...
我已经为这段代码写了一些基础,但是我想问一下在开始认真的骑自行车"之前还有什么其他方法.
I have wrote some base for this code but i wanted to ask what would be other approaches before i start the serious "for cyclying".
谢谢!
推荐答案
将字符串包装在实现可比性的新类中如何?
What about wrapping the String in a new Class that implements comparable?
可能是一些我尚未测试过的小案例.
May be some edge case bugs that i have not tested.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CompString {
public static void main(String[] args) {
List<ComparableString> list = new ArrayList<ComparableString>();
list.add(new ComparableString("apple"));
list.add(new ComparableString("stream"));
list.add(new ComparableString("posthouse"));
list.add(new ComparableString("sea"));
list.add(new ComparableString("seed"));
Collections.sort(list);
System.out.println(list);
}
}
class ComparableString implements Comparable<ComparableString> {
String str;
static String sortOrder = "qwertyuiosapdfghjklzcxvbnm";
public ComparableString(String string) {
str = string;
}
@Override
public String toString() {
return str;
}
@Override
public int compareTo(ComparableString other) {
for (int i = 0; i < Math.min(this.str.length(), other.str.length()); i++) {
int thisOrder = ComparableString.sortOrder.indexOf(this.str.charAt(i));
int thatOrder = ComparableString.sortOrder.indexOf(other.str.charAt(i));
int order = thisOrder - thatOrder;
if (order != 0) {
return order;
}
}
if (this.str.length() > other.str.length()) {
return -1;
} else if (this.str.length() < other.str.length()) {
return 1;
}
return 0;
}
}
这篇关于根据Java中的字符列表对单词列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文