List<Map>集合如何使用Stream流进行排序

编程入门 行业动态 更新时间:2024-10-07 13:19:45

List<Map>集合如何使用Stream<a href=https://www.elefans.com/category/jswz/34/1538330.html style=流进行排序"/>

List<Map>集合如何使用Stream流进行排序

起因:最近在工作中遇到一个问题,我从数据库中查询数据,返回的数据是一个List集合,且Map未指定类型。然后需要根据Map中的某个值对数组进行排序。虽然利用for循环可以完成这个工作,但是感觉代码太复杂,不美观而且不符合我们jdk1.8的特性。随决定使用Stream流进行排序。

1、我要查询根据月份查询数据,这是我的最开始返回的结果,可以看见第12月排在第一条了,我理想的数据是从1月开始。

[{"lastYear": [{"monthtime": "12","operationtime": 11033},{"monthtime": "01","operationtime": 0},{"monthtime": "02","operationtime": 0},{"monthtime": "03","operationtime": 0},{"monthtime": "04","operationtime": 0},{"monthtime": "05","operationtime": 0},{"monthtime": "06","operationtime": 0},{"monthtime": "07","operationtime": 0},{"monthtime": "08","operationtime": 0},{"monthtime": "09","operationtime": 0},{"monthtime": "10","operationtime": 0},{"monthtime": "11","operationtime": 0},]}
]

然后我就想着对该数据进行排序处理。因为流排序的效率非常高。
**

这是我自己编写的排序代码:

**

list.stream().sorted(Comparatorparing(map -> Integer.parseInt(map.get("monthtime").toString()))).collect(Collectors.toList());

看一下Comparatorparing的源码:

 * @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)pareTo(keyExtractor.apply(c2));
}

这个是函数式编程的特点,参数是一个方法,利用这个方法我们可以告诉排序方法我们需要根据什么来进行排序。我这里需要根据monthtime键对应的值进行排序,利用lambda表达式,把该函数传入即可。

排序后的结果:

[{"lastYear": [{"monthtime": "01","operationtime": 0},{"monthtime": "02","operationtime": 0},{"monthtime": "03","operationtime": 0},{"monthtime": "04","operationtime": 0},{"monthtime": "05","operationtime": 0},{"monthtime": "06","operationtime": 0},{"monthtime": "07","operationtime": 0},{"monthtime": "08","operationtime": 0},{"monthtime": "09","operationtime": 0},{"monthtime": "10","operationtime": 0},{"monthtime": "11","operationtime": 0},{"monthtime": "12","operationtime": 11033}]}
]

如有问题,请指正,谢谢!

更多推荐

List<Map>集合如何使用Stream流进行排序

本文发布于:2024-02-19 17:37:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1765276.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:流进   如何使用   List   Map   Stream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!