package cn.dj.demo.test;
import cn.dj.demo.domain.Student;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
public class TestPEEK {
public static void main(String[] args) {
/*
* peek接收一个Consumer,而map接收一个Function。
*
* Consumer是没有返回值的,它只是对Stream中的元素进行某些操作,
* 但是操作之后的数据并不返回到Stream中,所以Stream中的元素还是原来的元素。
*
* 而Function是有返回值的,这意味着对于Stream的元素的所有操作都会作为新的结果返回到Stream中。
*
*
* 这个还是不理解
* %%%%%%%%%
* 这就是为什么peek String不会发生变化而peek Object会发送变化的原因。
* %%%%%
* */
List<Student> studentList = new ArrayList<>();
studentList.add(new Student(1,"张三","23",new Date(),1));
studentList.add(new Student(1,"李四","24",new Date(),1));
studentList.add(new Student(1,"张瘦瘦","25",new Date(),1));
studentList.add(new Student(1,"李胖胖","26",new Date(),2));
studentList.add(new Student(1,"上课萨拉","33",new Date(),3));
List<String> stringList = new ArrayList<>();
stringList.add("q");
stringList.add("w");
stringList.add("e");
stringList.add("f");
stringList.add("g");
// peek 对我们创建的一些对象:如果我们更改了一些属性的值,对象list变化了
List<Student> collect = studentList.stream().peek(i -> {
// i.setSName("111");
i.setSClass(99);
}).collect(Collectors.toList());
for (Student student : collect) {
// System.out.println(student.getSName());
System.out.println(student.getSClass());
}
System.out.println("------------------");
// 2.如果我们操作的是一些如同的string,int这些,原先的流对象中的值并没有发生变化,
List<String> strColl = stringList.stream().peek(s -> {
s.toUpperCase();
}).collect(Collectors.toList());
for (String s : strColl) {
System.out.println(s);
}
System.out.println("---------------------");
// 3. 如果是使用map对流对象中的数据进行操作,那么流对象会发生变化
List<String> strCollByMap = stringList.stream().map(i -> {
return i.toUpperCase();
}).collect(Collectors.toList());
for (String o : strCollByMap) {
System.out.println(o);
}
}
}
package cn.dj.demo.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private Integer sId;
private String sName;
private String sAge;
private Date sBirthday;
private Integer sClass;
}
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>