Stream方法使用-filter、sorted、distinct、limit

简介: Stream方法使用-filter、sorted、distinct、limit

Stream方法使用

filter、sorted、distinct、limit

这几个都是常用的Stream的中间操作方法,具体的方法的含义在stream初相识篇里面有说明。具体使用的时候,可以根据需要选择一个或者多个进行组合使用,或者同时使用多个相同方法的组合:

publicvoidtestGetTargetUsers() {
List<String>ids=Arrays.asList("205","10","308","49","627","193","111", "193");
// 使用流操作List<Dept>results=ids.stream()
        .filter(s->s.length() >2)
        .distinct()
        .map(Integer::valueOf)
        .sorted(Comparator.comparingInt(o->o))
        .limit(3)
        .map(id->newDept(id))
        .collect(Collectors.toList());
System.out.println(results);
}

上面的代码片段的处理逻辑很清晰:

  1. 使用filter过滤掉不符合条件的数据
  2. 通过distinct对存量元素进行去重操作
  3. 通过map操作将字符串转成整数类型
  4. 借助sorted指定按照数字大小正序排列
  5. 使用limit截取排在前3位的元素
  6. 又一次使用map将id转为Dept对象类型
  7. 使用collect终止操作将最终处理后的数据收集到list中

输出结果:

[Dept{id=111}, Dept{id=193}, Dept{id=205}]


相关文章
|
6天前
【stream】List根据某个字段求和
【stream】List根据某个字段求和
5 0
|
5月前
|
Java 测试技术 Maven
stream-query
stream-query
65 0
|
SQL 分布式计算 Spark
SPARK Expand问题的解决(由count distinct、group sets、cube、rollup引起的)
SPARK Expand问题的解决(由count distinct、group sets、cube、rollup引起的)
561 0
SPARK Expand问题的解决(由count distinct、group sets、cube、rollup引起的)
ES6常用数组方法总结(max,contant,some,every,filter,reduce,forEach,map)
1.求最大值(Math.max) 2.数组添加到另外一个数组的尾部(...扩展符) 3.复制数组 3.1数组直接赋值 3.2 es5通过concat方法进行克隆,不会影响原来数组 3.3 es6通过扩展字符串来实现克隆 4.用Object.keys清空对象的属性值 5.forEach,遍历数组,无返回值,不改变原数组 6.map遍历数组,返回新数组,不改变原数组 7.filter,过滤掉数组不符合条件的值,返回新数组,不改变原数组 8.reduce 9 some() 10.every
145 0
ES6常用数组方法总结(max,contant,some,every,filter,reduce,forEach,map)
4.1、Array数组常用的方法(map、push、sort、filter、join、split)
4.1、Array数组常用的方法(map、push、sort、filter、join、split)
109 0
|
数据库
分页limit和排序order by
分页limit和排序order by
|
Serverless 索引 Python
内置函数 -- filter 和 map
Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
106 0
|
SQL 关系型数据库 MySQL
Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggre
Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggre
344 0
|
XML SQL 数据库
除了会排序,你对ORDER BY的用法可能一无所知!(二)
小伙伴们在进行SQL排序时,都能很自然的使用到ORDER BY。不管是默认ASC的升序,还是DESC降序,几乎都是信手拈来。 今天给大家分享一些你可能不知道的ORDER BY用法。
除了会排序,你对ORDER BY的用法可能一无所知!(二)
|
SQL 数据库
除了会排序,你对ORDER BY的用法可能一无所知!(一)
小伙伴们在进行SQL排序时,都能很自然的使用到ORDER BY。不管是默认ASC的升序,还是DESC降序,几乎都是信手拈来。 今天给大家分享一些你可能不知道的ORDER BY用法。
除了会排序,你对ORDER BY的用法可能一无所知!(一)