定义测试model类:
public class User {
private Integer age;
public User(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
测试类:
此处使用最简单的匿名内部类实现重写比较函数,虚拟参数为o1,o2,返回值为 o1-o2(也可以返回 JDk默认的比较参数 -1,0,1用来比较大小),这样就实现了升序排序。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Comparator_test {
public static void main(String[] args) {
List<User> integerList = new ArrayList<User>() {{
add(new User(1));
add(new User(5));
add(new User(3));
}};
Collections.sort(integerList, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
return o1.getAge()-o2.getAge();
}
});
Collections.reverse(integerList);
integerList.forEach(System.out::println);
}
}
//使用lambda表达式代替匿名内部类,查看Compatator 知道,在JDk 1.8 中此接口添加了
@FunctionalInterface,成为了一个函数式接口,而lamda可以用表达式或函数体表示,因此这里可以使用lambda简化代码。
(o1, o2) -> o1.getAge()-o2.getAge() ,此处,定义了两个参数,功能是返回两者的差值,作用与匿名内部类相同。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Comparator_test {
public static void main(String[] args) {
List<User> integerList = new ArrayList<User>() {{
add(new User(1));
add(new User(5));
add(new User(3));
}};
Collections.sort(integerList, (o1, o2) -> o1.getAge()-o2.getAge());
Collections.reverse(integerList);
integerList.forEach(System.out::println);
}
}
//使用函数代替lambda
查看
Comparator<T>源码可知,新添加了返回比较器的方法,Comparator.comparingInt(User::getAge)
源码如下:
/**
* Accepts a function that extracts an {@code int} sort key from a type
* {@code T}, and returns a {@code Comparator<T>} that compares by that
* sort key.
*
* <p>The returned comparator is serializable if the specified function
* is also serializable.
*
* @param <T> the type of element to be compared
* @param keyExtractor the function used to extract the integer sort key
* @return a comparator that compares by an extracted key
* @see #comparing(Function)
* @throws NullPointerException if the argument is null
* @since 1.8
*/
public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) {
Objects.requireNonNull(keyExtractor);
return (Comparator<T> & Serializable)
(c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));
}
参数还是函数式接口,方法体返回的功能即上个方法中lambda表达式的功能,因此这里可以再次化简我们的代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Comparator_test {
public static void main(String[] args) {
List<User> integerList = new ArrayList<User>() {{
add(new User(1));
add(new User(5));
add(new User(3));
}};
Collections.sort(integerList, Comparator.comparingInt(User::getAge));
Collections.reverse(integerList);
integerList.forEach(System.out::println);
}
}