Java8:流式编程
编写:HorinJsor
前言
本文介绍Java8的特性之【流式编程】。
提示:以下是本篇文章正文内容,下面案例可供参考
一、流式编程
流式编程是Java8的特性,可以替换传统的代码编写方式,提升可读性。
可以理解为梭哈(搞怪)。
Lambda: ( 参数 -> 执行方法 )
二、实例
1.基础三剑客
@SpringBootTest
public class StreamTeat {
/**
创建List<Apple>对象,以此示例展示流的操作
**/
public List<Apple> b(){
Apple apple1 = new Apple("red",200,"cq");
Apple apple2 = new Apple("red", 300, "cd");
Apple apple3 = new Apple("white", 900, "gx");
List<Apple> all = new ArrayList<>();
all.add(apple1);all.add(apple2);all.add(apple3);
return all;
}
@Test
public void a(){
//获取对象
List<Apple> all = b();
all.stream() //【创建流】:将对象转换为流,将List打碎成流,以apple形式传输
.filter(a -> a.getColor().equals("red")) //【过滤,保留true的东西】:保留颜色为红色的苹果对象
.peek(a -> System.out.println(a.getColor()+":"+a.getCity())) //相当于一个执行方法
.toArray(); //【终止节点,流转换为对象】:将流转换为Array对象,否则不能输出
}
}
2.映射转换【 map() 】
@Test
public void c(){
List<Apple> all = b();
all.stream()
.filter(a -> a.getColor().equals("red"))
.map(a -> a.getColor()) //【映射】:a的color属性
.peek(color -> System.out.println(color)) //此时color参数为字符串
.toArray();
}
方法 | 作用 |
---|---|
distinct() | 去除重复元素 |
forEach() | 终止节点,可执行方法 |
3.排序[ sorted((T, T) -> int) ]
@Test
public void c(){
List<Apple> all = b();
all.stream()
.sorted((p1,p2) -> (int) (p2.getWeight() - p1.getWeight())) //重量由大到小排序
.peek(a -> System.out.println(a.getColor() + ":"+a.getWeight()))
.collect(Collectors.toList());
}
总结
冲。
更多函数请访问:
lambda之Stream流式编程
java8之Stream流处理