peek用于处理集合中元素(对象)的某个属性的值,但不改变元素(对象)的类型(区别于map操作),举例如下:
package listDemo;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamPeekDemo {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("xiaozhang", 20));
personList.add(new Person("xiaowang", 21));
List<Person> peekedList = personList.stream().peek(e -> e.setCity("beijing")).collect(Collectors.toList());
System.out.println(StringUtils.join(peekedList, "-"));
}
}
package listDemo;
import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
@Data
@RequiredArgsConstructor
public class Person {
@NonNull
private String name;
@NonNull
private int age;
private String city;
}
运行结果如下:
Person(name=xiaozhang, age=20, city=beijing)-Person(name=xiaowang, age=21, city=beijing)