前言
平时操作集合数据,我们一般都是for或者iterator去遍历,不是很好看。java提供了Stream的概念,它可以让我们把集合数据当做一个个元素在处理,并且提供多线程模式
流的创建
流的各种数据操作
流的终止操作
流的聚合处理
并发流和CompletableFuture的配合使用
「关注公众号,一起交流,微信搜一搜: 潜行前行」
1 stream的构造方式
stream内置的构造方法
public static Stream iterate(final T seed, final UnaryOperator f)
public static Stream concat(Stream extends T> a, Stream extends T> b)
public static Builder builder()
public static Stream of(T t)
public static Stream empty()
public static Stream generate(Supplier s)
Collection声明的stream函数
default Stream stream()
Collection声明了stream转化函数,也就是说,任意Collection子类都存在官方替我们实现的由Collection转为Stream的方法
示例,List转Stream
public static void main(String[] args){
List demo = Arrays.asList("a","b","c");
long count = demo.stream().peek(System.out::println).count();
System.out.println(count);
}
-------result--------
a
b
c
3
2 接口stream对元素的操作方法定义
过滤 filter
Stream filter(Predicate super T> predicate)
Predicate是函数式接口,可以直接用lambda代替;如果有复杂的过滤逻辑,则用or、and、negate方法组合
示例
List demo = Arrays.asList("a", "b", "c");
Predicate f1 = item -> item.equals("a");
Predicate f2 = item -> item.equals("b");
demo.stream().filter(f1.or(f2)).forEach(System.out::println);
-------result--------
a
b
映射转化 map
Stream map(Function super T, ? extends R> mapper)
IntStream mapToInt(ToIntFunction super T> mapper);
LongStream mapToLong(ToLongFunction super T> mapper);
DoubleStream mapToDouble(ToDoubleFunction super T> mapper);
示例
static class User{
public User(Integer id){this.id = id; }
Integer id; public Integer getId(){ return id; }
}
public static void main(String[] args){
List demo = Arrays.asList(new User(1), new User(2), new User(3));
// User 转为 Integer(id)
demo.stream().map(User::getId).forEach(System.out::println);
}
-------result--------
1
2
3
数据处理 peek
Stream peek(Consumer super T> action);
与map的区别是其无返回值
示例
static class User{
public User(Integer id){this.id = id; }
Integer id;
public Integer getId(){ return id; }
public void setId(Integer id){ this.id = id; }
}
public static void main(String[] args){
List demo = Arrays.asList(new User(1), new User(2), new User(3));
// id平方,User 转为 Integer(id)
demo.stream().peek(user -> user.setId(user.id * user.id)).map(User::getId).forEach(System.out::println);
}
-------result--------
1
4
9
映射撵平 flatMap
Stream flatMap(Function super T, ? extends Stream extends R>> mapper);
IntStream flatMapToInt(Function super T, ? extends IntStream> mapper);
LongStream flatMapToLong(Function super T, ? extends LongStream> mapper);
DoubleStream flatMapToDouble(Function super T, ? extends DoubleStream> mapper);
flatMap:将元素为Stream类型的流撵平成一个元素类型为T的Stream流
示例
public static void main(String[] args){
List> demo = Arrays.asList(Stream.of(5), Stream.of(2), Stream.of(1));
demo.stream().flatMap(Function.identity()).forEach(System.out::println);
}
-------result--------
5
2
1