以前在内存中用大数据量的排序不论使用
冒泡排序
还是使用Collections.sort
效率都相当低下,现如今Java 8 出现了Comparator
首先这并不是一个方法,而是一个接口
@FunctionalInterface
public interface Comparator<T> {
}
在此不过多阐述它实现的原理,只在这里介绍它的两个实现方法
/**
* Accepts a function that extracts a {@link java.lang.Comparable
* Comparable} 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.
*
* @apiNote
* For example, to obtain a {@code Comparator} that compares {@code
* Person} objects by their last name,
*
* <pre>{@code
* Comparator<Person> byLastName = Comparator.comparing(Person::getLastName);
* }</pre>
*
* @param <T> the type of element to be compared
* @param <U> the type of the {@code Comparable} sort key
* @param keyExtractor the function used to extract the {@link
* Comparable} sort key
* @return a comparator that compares by an extracted key
* @throws NullPointerException if the argument is null
* @since 1.8
*/
public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
Function<? super T, ? extends U> keyExtractor)
{
Objects.requireNonNull(keyExtractor);
return (Comparator<T> & Serializable)
(c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}
/**
* Returns a comparator that imposes the reverse ordering of this
* comparator.
*
* @return a comparator that imposes the reverse ordering of this
* comparator.
* @since 1.8
*/
default Comparator<T> reversed() {
return Collections.reverseOrder(this);
}
一、comparing 方法的使用
从注释信息不难看出
comparing
方法 传入一个函数,这个函数携带一个参数,参数类型为List对象或者JSONArray对象
例子:
//json 字符串
String dd = "[{id:1,adress:上海,age:21},{id:2,adress:上海,age:32},{id:3,adress:上海,age:28},{id:4,adress:上海,age:27}]";
//字符串转对象
JSONArray listObjectFifth = JSONObject.parseArray(dd);
//根据age升序排序
listObjectFifth.sort(Comparator.comparing(obj -> ((JSONObject) obj).getBigDecimal("age")));
二、reversed 方法的使用
从注释信息不难看出
reversed
方法返回一个比较器,而且是强制执行此逆序
例子:
//json 字符串
String dd = "[{id:1,adress:上海,age:21},{id:2,adress:上海,age:32},{id:3,adress:上海,age:28},{id:4,adress:上海,age:27}]";
//字符串转对象
JSONArray listObjectFifth = JSONObject.parseArray(dd);
//根据age降序排序
listObjectFifth.sort(Comparator.comparing(obj -> ((JSONObject) obj).getBigDecimal("age")).reversed());