我正在尝试对具有包含整数和字母的字符串的列表数组进行排序,但是当我按常规方式进行操作时,我会得到一些奇怪的输出: 相关代码:
List<String> words = new ArrayList<>();
words.add("9 hello");
words.add("98 food");
words.add("105 cat");
words.add("2514 human");
words.add("3 pencil");
words.sort(Comparator.reverseOrder());
我期待着:
"2514 human"
"105 cat"
"98 food"
"9 hello"
"3 pencil"
但是我得到这样的东西:
"98 food"
"9 hello"
"3 pencil"
"2514 human"
"105 cat"
有什么建议吗?
答案 0 :(得分:0)
使用Comporator可以解决您的问题
将此代码添加到您的班级内
private static Comparator<String> ORDER_MYLIST = new Comparator<String>() {
public int compare(String d, String d1) {
int first = Integer.parseInt(d.split(" ")[0]);//since you have space
int second = Integer.parseInt(d1.split(" ")[0]);
return second - first;//change the order if you want
}
};
将此代码添加到您的调用函数中
Collections.sort(words, ORDER_MYLIST);
输出:
[2514 human, 105 cat, 98 food, 9 hello, 3 pencil]
会如您所愿。
此链接将使您更好地了解Comporator的工作方式 https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
答案 1 :(得分:0)
我认为您应该创建一个类来表示列表中的元素。 例如:
public class WordCount {
public static final Comparator<WordCount> BY_COUNT;
private static final Pattern PATTERN
= Pattern.compile("\\s*([0-9]+)\\s+(.*)");
public final int count;
public final String word;
public static WordCount parse(String s) {
Matcher matcher = PATTERN.matcher(s);
if (!matcher.matches()) {
throw new IllegalArgumentException("Syntax error: " + s);
}
return new WordCount(
Integer.parseInt(matcher.group(1)), matcher.group(2));
}
public WordCount(int count, String word) {
this.count = count;
this.word = word;
}
@Override
public String toString() {
return count + " " + word;
}
static {
BY_COUNT = (WordCount o1, WordCount o2) -> {
int r = Integer.compare(o1.count, o2.count);
if (r == 0) {
r = o1.word.compareTo(o2.word);
}
return r;
};
}
}
您的代码将变为:
List<WordCount> words = new ArrayList<>();
words.add(WordCount.parse("9 hello"));
words.add(WordCount.parse("98 food"));
words.add(WordCount.parse("105 cat"));
words.add(WordCount.parse("2514 human"));
words.add(WordCount.parse("3 pencil"));
words.sort(WordCount.BY_COUNT.reversed());
words.forEach((wc) -> {
System.out.println(wc);
});
具有以下结果:
2514 human
105 cat
98 food
9 hello
3 pencil
答案 2 :(得分:0)
您需要一个自定义比较器来满足您的要求。 Java 8解决方案:
List<String> words = new ArrayList<>();
words.add("9 hello");
words.add("98 food");
words.add("105 cat");
words.add("2514 human");
words.add("3 pencil");
// Sort the existing list
words.sort(Comparator.comparing(s -> Integer.parseInt(s.split(" ")[0]), Comparator.reverseOrder()));
// To create new sorted list
List<String> sortedWords = words.stream()
.sorted(Comparator.comparing(s -> Integer.parseInt(s.split(" ")[0]), Comparator.reverseOrder()))
.collect(Collectors.toList());
答案 3 :(得分:-1)
您得到的正是按字母顺序排列的顺序,因为不是数字被比较,而是数字按字母顺序排序。
如果您想要其他行为,则应考虑实现自己的Comparator
,在其中解析数字。