案例数据
public class test01 {
public List<Double> list=new ArrayList<>();
@Before
public void init(){
list.addAll(Arrays.asList(1.1,2.2,5.5,3.3,4.4,1.1));
}
@Test
public void test01(){
}
}
1.去除流中重复、并排序操作
@Test
public void test01(){
List<Double> collect = list.stream().distinct().sorted().collect(Collectors.toList());
System.out.println(collect);
}
stream:将列表转换为流
distinct:去除重复元素
sorted:排序操作
collect:收集流中的元素并返回相应对象
distinct 是调用的是流中元素的equals()方法
sorted 调用的是流中元素的compareTo()方法
collect 这个比较复杂,就大概知道传入Collectors这个类的一些的方法可以决定流元素收集后返回的对象Collectors.toList()
对collect再举个例子 将这个流收集成map
@Test
public void test01(){
Map<Double, Double> collect = list.stream().distinct().sorted((i, j) -> i.compareTo(j))
.collect(Collectors.toMap(i -> i, j -> j + 1.0));
System.out.println(collect);
}
这个的意思就是将流的元素作为key,元素+1就是value
2.做一个用流进行数据处理的案例
@Test
public void test02(){
BigDecimal reduce = list.stream().map(BigDecimal::valueOf).reduce(BigDecimal::add).get();
System.out.println(reduce);
}
map 对流数据进行处理,将流中的double对象转为BigDecimal对象
reduce 对流中的数据进行处理 结果会累计
get 获取结果
这个写法是函数引用,也可以以用下面的写法
@Test
public void test02(){
BigDecimal reduce = list.stream().map(i->BigDecimal.valueOf(i)).reduce((i,j)->i.add(j)).get();
System.out.println(reduce);
}
为什么要举这个例子?
double对象一般不用来进行计算,因为计算机存储的原因,进行计算会出现精度问题所以需要专门 的BigDecimal类进行计算处理
如果遇到一些数据库查回来小数,又需要进行计算可以使用这种写法
3.排除不希望要的元素
这个比较简单了,举个例子不希望要小于3.0的数据
@Test
public void test03(){
List<Double> collect = list.stream().filter(i -> i > 2.0).collect(Collectors.toList());
System.out.println(collect);
}
返回true则留下返回false则去掉
总结
流操作还是很方便的,有些方法看着名字也能大概才出来是干啥用的,主要还是理解流式操作到底是什么,方法里的参数匿名函数、方法引用的作用。