Java 8 Streams peek
流由三部分构成:数据源,一个或多个中间操作,一个或多个终止操作。
数据源:为流提供数据。
中间操作:依次获取数据并处理数据。所有的中间操作都是“懒操作”,也就是说在流开始工作之前,中间操作对流中的数据没有任何影响。
终止操作:流生命周期的结束,它可以触发流开始工作,中间操作也就会影响流中的数据。
peek 单独执行不起作用,如
@Test
public void test_printInfo() {
Person a = new Person("a", 18);
Person b = new Person("b", 23);
Person c = new Person("c", 34);
Stream<Person> persons = Stream.of(a, b, c);
persons.forEach(System.out::println);
}
Person{name='a', age=18}
Person{name='b', age=23}
Person{name='c', age=34}
peek不可用来改变流中对象引用,但可以用来修改内部属性.对比map来修改属性,会更加方便,但map可用改变流的对象引用.
@Test
public void test_modifyInnerState() {
Person a = new Person("a", 18);
Person b = new Person("b", 23);
Person c = new Person("c", 34);
Stream<Person> persons = Stream.of(a, b, c);
persons.peek(person -> person.setName(person.getName().toUpperCase()))
.forEach(System.out::println);
}
Person{name='A', age=18}
Person{name='B', age=23}
Person{name='C', age=34}
以下代码不起作用,因为peek不会改变流中数据的引用.
Stream.of("a","b","c").peek(s -> s = s.toUpperCase()).forEach(System.out::println);