java stream详解

Stream数据源

1. Collection
2. Arrays

Stream流处理逻辑

数据源(datasource) --> 数据转换(中间操作) -->数据转换(中间操作) -->执行操作获取结果(终止操作)

Stream创建

  1. 通过collection创建( collection.stream() or collection.parallelStream()方法)
Collection<String> collection = new ArrayList<>();
Stream stream = collection.stream();
stream = collection.parallelStream();
  1. 通过Arrays创建
 String[] userNameArr = new String[]{"zhangsan", "lisi", "wangwu"};
 Stream stream = Arrays.stream(userNameArr);
  1. Stream的静态方法of
Stream stream = Stream.of("zhangsan", "lisi", "wangwu");

4.Stream的静态方法empty

Stream stream = Stream.empty();

Stream方法

stream方法主要分为两种:中间操作方法和终止操作方法

中间操作方法(指那些返回stream的方法)

方法 描述
filter 将流中符合条件的元素组成新的流
limit 截断,使元素不超过给定数量
skip 跳过元素,返回一个扔掉了前n个元素的流,如果流中不足n个,返回一个空流
skip操作与limit互补
distinct 通过流产生的元素的hashCode()和equals()去除重复元素
map(Function mapper) 将流中所有的元素执行mapper操作将结果生成新的stream

终止操作方法

方法 描述
count() 返回流中元素个数
findFirst() 返回流中第一个元素
noneMatch(Predicate predicate) 返回流中是否没有符合条件的元素,如果是,返回true,否则返回false
allMatch(Predicate predicate) 返回流中是否所有的元素都满足条件
anyMatch(Predicate predicate) 流中是否存在一个或以上的元素满足条件
max(Comparator comparator) 根据comparator算法获取流中最大的元素
min(Comparator comparator) 根据comparator算法获取流中最小的元素
collect(Collector collector) 将流中的元素收集到另一个目标中
toArray 将流中的元素转换为数组

collect()方法常用使用方法

List<String> result = stream.collect(Collections.tolist());
Set<String> result = stream.collect(Collections.toSet());
TreeSet<String> result = stream.collect(Collectors.toCollection(Treeset::new));
String result = stream.collect(Collectors.joining());

你可能感兴趣的:(java,开发语言)