链式编程与流式计算基础
“集合讲的是数据,流讲的是计算”
前言
有关链式编程与流式计算的具体原理会写在Scala中,在这里以Java中的实现为主。
实现
Lombok与链式编程的简单Demo
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
class User {
private int id;
private String userName;
private int age;
}
public class StreamDemo {
public static void main(String[] args) {
new User().setUserName("test").setId(12).setAge(12);
}
}
四大函数接口
在java.util.function中定义了以下四大函数式接口
- Consumer
输入T,无返回值 - Supplier
无输入值,返回T - Function<T, R> 输入T,返回R
- Predicate
输入T,返回Booleanf
在java.util.steam中书写了如下规则:
int sum = widgets.stream()
.filter(b -> b.getColor() == RED)
.mapToInt(b -> b.getWeight())
.sum()
filter,map方法
list.stream().filter(u -> {
return u.getId() % 2 == 0;
});
//collect(collectors.tolist())将collect再次转回list
list.stream.map(x -> {return x * 2;}).collect(collectors.tolist());
list.stream().filter(u -> {
return u.getId() % 2 == 0;
}).filter(t -> {
return t.getAge() > 24;
}).map(m -> {
return m.getUserName().toUpperCase();
}).sorted((o1,o1) -> {
return o2.compareTo(o1);
}).count.foreach(System.out::println);