lamda 部分使用

154 阅读1分钟

java特性

概况

特性
流只能运行一次
流由源 0个或者多个中间操作以及结束操作组成
流的中间操作是惰性的并不会立即执行 这更有利于内部迭代的优化
流借助于它内部迭代特性提供了声明式的编程方式 更急简洁
中间操作本身会返回一个流,可以将多个操作复合叠加,形成一个更大的流水线
流分为顺序和并行两种方式

中间操作和终结操作

中间操作 终结操作
filter() flatMap() limit() map()  concat() distinct() peek() skip() sorted() parallel() sequential() unordered()  flatMapTo mapTo allMatch() anyMatch() collect() count() findAny() findFirst() forEach() forEachOrdered() max() min() noneMatch() reduce() toArray()

collectors类

toList

生成字符串,多数配合map,filter之类配合collect终止操作作为stream终止 jdk自带demo

List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());

toCollection

对于其他类的收集操作,配合collect终止操作作为stream终止

Set<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new));

groupingBy

分组

      Map<Department, List<Employee>> byDept
          = employees.stream()
                     .collect(Collectors.groupingBy(Employee::getDepartment));

joining

 *     // Convert elements to strings and concatenate them, separated by commas
 *     String joined = things.stream()
 *                           .map(Object::toString)
 *                           .collect(Collectors.joining(", "));

collectingAndThen

重新进行操作,去重demo

            List<SysEmployeeVo> distinctEmployeeVos = employeeVos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(SysEmployeeVo::getEmployeeName))),ArrayList::new));