今天在某个推文中看到说stream流是可读流,类似于数据库查询操作,只能查询数据,不会保存数据。这个说法有悖于我常用stream遍历对象并重新set属性。所以做了个测试程序
package com.logisitics.job.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
static class A{
int age;
String name;
A(){}
A(int age,String name){
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "A{" +
"age=" + age +
", name='" + name + '\'' +
"内存地址:" + super.toString() +
'}';
}
}
public static void main(String[] args) {
A a = new A(21 , "wxy");
A b = new A(22 , "xy");
A c = new A(23 , "y");
List<A> list = new ArrayList<>();
list.add(a);
list.add(b);
list.add(c);
list.stream().peek(e-> {
System.out.println("当前e对象-peek:"+e.toString());
e.setAge(30);
}).filter(e -> {
System.out.println("当前e对象-filter:"+e.toString());
return true;
}).collect(Collectors.toList());
System.out.println("----------");
for (A a1 : list) {
System.out.println("当前对象-foreach:"+a1.toString());
}
System.out.println("----------");
List<Integer> list1 = new ArrayList<>(Arrays.asList(1,2,3,4,5));
list1.stream().peek(e-> {
System.out.println("当前e对象-peek:"+e.toString() + "值:"+e);
e = 5;
}).filter(e -> {
System.out.println("当前e对象-filter:"+e.toString() + "值:"+e);
return true;
}).collect(Collectors.toList());
}
}
输出值为:
当前e对象-peek:A{age=21, name='wxy'内存地址:com.logisitics.job.util.Test$A@5c0369c4}
当前e对象-filter:A{age=30, name='wxy'内存地址:com.logisitics.job.util.Test$A@5c0369c4}
当前e对象-peek:A{age=22, name='xy'内存地址:com.logisitics.job.util.Test$A@2be94b0f}
当前e对象-filter:A{age=30, name='xy'内存地址:com.logisitics.job.util.Test$A@2be94b0f}
当前e对象-peek:A{age=23, name='y'内存地址:com.logisitics.job.util.Test$A@d70c109}
当前e对象-filter:A{age=30, name='y'内存地址:com.logisitics.job.util.Test$A@d70c109}
----------
当前对象-foreach:A{age=30, name='wxy'内存地址:com.logisitics.job.util.Test$A@5c0369c4}
当前对象-foreach:A{age=30, name='xy'内存地址:com.logisitics.job.util.Test$A@2be94b0f}
当前对象-foreach:A{age=30, name='y'内存地址:com.logisitics.job.util.Test$A@d70c109}
----------
当前e对象-peek:1值:1
当前e对象-filter:1值:1
当前e对象-peek:2值:2
当前e对象-filter:2值:2
当前e对象-peek:3值:3
当前e对象-filter:3值:3
当前e对象-peek:4值:4
当前e对象-filter:4值:4
当前e对象-peek:5值:5
当前e对象-filter:5值:5
首先是针对于对象来说 , 无论是中间操作还是终止操作,都不会改变对象的引用,但可以改变对象中属性的值;且流的操作是从前往后的,不是从后往前。
后针对于普通包装类,以Integer为例子:
是无法改变元素的值的,因为对于Integer来说,其值为固定的(无论Integer值是否大于-128-127)
所以证明了流中元素确实只能读取无法保存数据;
|