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); }
上面的代码片段的处理逻辑很清晰:
- 使用filter过滤掉不符合条件的数据
- 通过distinct对存量元素进行去重操作
- 通过map操作将字符串转成整数类型
- 借助sorted指定按照数字大小正序排列
- 使用limit截取排在前3位的元素
- 又一次使用map将id转为Dept对象类型
- 使用collect终止操作将最终处理后的数据收集到list中
输出结果:
[Dept{id=111}, Dept{id=193}, Dept{id=205}]