@Test
public void testOrdering() {
List<Integer> numbers = Lists.newArrayList(30, 20, 60, 80, 10);
List<Integer> result=Lists.newArrayList();
result=Ordering.natural().sortedCopy(numbers); // 10,20,30,60,80
result=Ordering.natural().reverse().sortedCopy(numbers); // 80,60,30,20,10
Integer min=Ordering.natural().min(numbers); // 10
Integer max=Ordering.natural().max(numbers); // 80
Lists.newArrayList(30, 20, 60, 80, null, 10);
Ordering.natural().nullsLast().sortedCopy(numbers); // 10,
// 20,30,60,80,null
Ordering.natural().nullsFirst().sortedCopy(numbers); // null,10,20,30,60,80
//natural() 对可排序类型做自然排序,如数字按大小,日期按先后排序
//usingToString() 按对象的字符串形式做字典排序[lexicographical ordering]
//from(Comparator) 把给定的Comparator转化为排序器
//reverse() 获取语义相反的排序器
//nullsFirst() 使用当前排序器,但额外把null值排到最前面。
//nullsLast() 使用当前排序器,但额外把null值排到最后面。
//自定义排序
List<Person> personList = Lists.newArrayList(new Person(1, "张三", "46546"),
new Person(2, "李四", "46546"),
new Person(3, "王五", "46546"),
new Person(4, "赵六", "46546"),
new Person(5, "钱七", "46546"));
Ordering<Person> byIDOrder = new Ordering<Person>() {
@Override
public int compare(Person left, Person right) {
return right.getId() - left.getId(); //大于1
}
};
//便利
for (Person p : byIDOrder.immutableSortedCopy(personList)) {
System.out.println(p.getName());
}
}
guava之list排序
最新推荐文章于 2023-02-15 14:15:47 发布