Guava教程
Ordering(排序)可以被看作是一个丰富的比较具有增强功能的链接,多个实用方法,多类型排序功能等。
以下是com.google.common.collect.Ordering<T>类的声明:
@GwtCompatible
public abstract class Ordering<T>
extends Object
implements Comparator<T>
类方法
这个类从以下类继承的方法:java.lang.Object
使用所选择的编辑器,创建下面的java程序比如 C:/> Guava
GuavaTester.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.common.collect.Ordering;
public class GuavaTester {
public static void main(String args[]){
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(new Integer(5));
numbers.add(new Integer(2));
numbers.add(new Integer(15));
numbers.add(new Integer(51));
numbers.add(new Integer(53));
numbers.add(new Integer(35));
numbers.add(new Integer(45));
numbers.add(new Integer(32));
numbers.add(new Integer(43));
numbers.add(new Integer(16));
Ordering ordering = Ordering.natural();
System.out.println("Input List: ");
System.out.println(numbers);
Collections.sort(numbers,ordering );
System.out.println("Sorted List: ");
System.out.println(numbers);
System.out.println("======================");
System.out.println("List is sorted: " + ordering.isOrdered(numbers));
System.out.println("Minimum: " + ordering.min(numbers));
System.out.println("Maximum: " + ordering.max(numbers));
Collections.sort(numbers,ordering.reverse());
System.out.println("Reverse: " + numbers);
numbers.add(null);
System.out.println("Null added to Sorted List: ");
System.out.println(numbers);
Collections.sort(numbers,ordering.nullsFirst());
System.out.println("Null first Sorted List: ");
System.out.println(numbers);
System.out.println("======================");
List<String> names = new ArrayList<String>();
names.add("Ram");
names.add("Shyam");
names.add("Mohan");
names.add("Sohan");
names.add("Ramesh");
names.add("Suresh");
names.add("Naresh");
names.add("Mahesh");
names.add(null);
names.add("Vikas");
names.add("Deepak");
System.out.println("Another List: ");
System.out.println(names);
Collections.sort(names,ordering.nullsFirst().reverse());
System.out.println("Null first then reverse sorted list: ");
System.out.println(names);
}
}
验证结果
使用javac编译器编译如下类
C:\Guava>javac GuavaTester.java
现在运行GuavaTester看到的结果
C:\Guava>java GuavaTester
看到结果
Input List:
[5, 2, 15, 51, 53, 35, 45, 32, 43, 16]
Sorted List:
[2, 5, 15, 16, 32, 35, 43, 45, 51, 53]
======================
List is sorted: true
Minimum: 2
Maximum: 53
Reverse: [53, 51, 45, 43, 35, 32, 16, 15, 5, 2]
Null added to Sorted List:
[53, 51, 45, 43, 35, 32, 16, 15, 5, 2, null]
Null first Sorted List:
[null, 2, 5, 15, 16, 32, 35, 43, 45, 51, 53]
======================
Another List:
[Ram, Shyam, Mohan, Sohan, Ramesh, Suresh, Naresh, Mahesh, null, Vikas, Deepak]
Null first then reverse sorted list:
[Vikas, Suresh, Sohan, Shyam, Ramesh, Ram, Naresh, Mohan, Mahesh, Deepak, null]
转载自并发编程网-ifeve.com