Sup*_*ing 3 java sorting tuples
我正在构建一个具有字符串到整数的映射的类.所以,如果我有3个苹果,我会将苹果映射到3个.
我需要编写一个类,通过减少数字来排序对象的名称.
所以,如果我有
(苹果,3)(橙子,2)(香蕉,5)
我会得到(香蕉,5),(苹果,3),(橙子2)
我想知道是否已经有一个课程可以让我的生活更轻松,或者我将如何实现这一点.
谢谢.
您应该能够将对象(苹果,3)(橙子,2)(香蕉,5)放入List中,然后调用Collections.sort(yourlist).然后,您需要确保声明的对象实现Comparable接口.
有关更多信息,请访问http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
假设你宣称你反对为
public class FruitAndCount implements Comparable<FruitAndCount> {
private final String name;
private final Integer count;
public FruitAndCount(String name, int count) {
this.name = name;
this.count = count;
}
public String name() { return name; }
public int count() { return count; }
public int compareTo(FruitAndCount o) {
return this.count.compareTo(o.count);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您应该能够进行以下调用,对您的列表进行排序:
FruitAndCount fruitArray[] = {
new FruitAndCount("Apples", 3),
new FruitAndCount("Oranges", 2),
new FruitAndCount("Bananas", 5)
};
List<FruitAndCount> fruit = Arrays.asList(fruitArray);
Collections.sort(fruit);
Run Code Online (Sandbox Code Playgroud)
然后你应该有一个排序的水果列表.
| 归档时间: |
|
| 查看次数: |
3314 次 |
| 最近记录: |