java 8 对JSONArray 按指定字段排序,升序和倒序,经典

文章目录

  • java 8 对JSONArray 按指定字段排序,升序和倒序,经典
    • 一、comparing 方法的使用
    • 二、reversed 方法的使用

java 8 对JSONArray 按指定字段排序,升序和倒序,经典

以前在内存中用大数据量的排序不论使用冒泡排序还是使用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} that compares by that sort key.
     *
     * 

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, * *

{@code
     *     Comparator byLastName = Comparator.comparing(Person::getLastName);
     * }
* * @param the type of element to be compared * @param 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());

1.如果想详细学习这些方法的实现原理请君移步到Oracle官网进行学习
2.Java 学习交流群欢迎你的到来 821605718

你可能感兴趣的:(java)