我有一个清单:
List<List<Item>> = [["a", "one", 3], ["b", "one", 2], ["c", "one", 4], ["d", "two", 2],["e", "one", 1], ["f", "two", 1]]
我想按子数组中的第二个值对它进行排序,如果有两个点,则应按第三个值排序,如果从那里找到两个点,则应按第一个元素对其进行排序。
因此,最终结果应如下所示:
[["e", "one", 1], ["b", "one", 2], ["a", "one", 3], ["c", "one", 4], ["f", "two", 1], ["d", "two", 2]]
有人可以教我一些好方法吗?
谢谢!
最佳答案
["a", "one", 3]
应该是您的类的实例,例如
class Item{
private String val1;
private String val2;
private int val3;
//getters and setters
}
这样,您的列表将是
List<Item>
。现在,您可以简单地使用Collections.sort(list, yourComparator)
或使用Java 8 list.sort(yourComparator)
。作为
yourComparator
,您可以传递实现Comparator
接口的类的实例,例如以一种方式Comparator<Item> yourComparator = new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
//comapre val2
int result = o1.getVal2().compareTo(o2.getVal2());
if (result != 0) return result;
//if we are here val2 in both objects ware equal (result was 0)
result = Integer.compare(o1.getVal3(), o2.getVal3());
if (result != 0) return result;
return o1.getVal1().compareTo(o2.getVal1());
}
};
但是可能更具可读性和可能更容易的方法是为每个字段创建单独的比较器并将其组合。如果您使用的是Java 8,则代码如下所示:
Comparator<Item> val1Comparator = Comparator.comparing(Item::getVal1);
Comparator<Item> val2Comparator = Comparator.comparing(Item::getVal2);
Comparator<Item> val3Comparator = Comparator.comparingInt(Item::getVal3);
list.sort(val2Comparator
.thenComparing(val3Comparator)
.thenComparing(val1Comparator));