使用流
筛选和切片
list.stream()
.filter(StringUtils::isNotEmpty)
.distinct() //筛选个异的元素
.skip(3) //跳过元素
.limit(3) //截断流
映射
list.stream()
.map(s->s.split(“”))//将字符串映射为数组
.flatMap(Arrays::stream) //将各个流生成扁平流
查找和匹配
boolean match = list.stream().allMatch(s->s.length>1);
boolean match = list.stream().anyMatch(s->”true”.eqeuals(s));
boolean match = list.stream().noneMatch(s->s.length<=1);
Optional hint = list.stream().filter(StringUtils::isNotEmpty).findAny();
Optional hint = list.stream().filter(StringUtils::isNotEmpty).findFirst();
归约reduce
int total = ints.stream().reduce(1, (a,b) -> a*b);
Optional total = ints.stream().reduce((a,b) -> a*b);
Optional max= ints.stream().reduce(Integer::max);
构建流
//由值创建
Stream stream = Stream.of(“a”,”b”);
//由数组创建
Stream stream = Stream.of(new String[]{“a”,”b”});
//由函数生成无限流
Stream.iterate(0,n->n+2).limit(10);//依次生成一系列的值
Stream.generate(Match::random).limit(10);//根据生成器产生值
用流收集数据
归约和汇总
//import static java.util.stream.Collectors.*;
Optional longest = list.stream().collect(maxBy((a,b)->a.length()-b.length()));
int length = list.stream().collect(summingInt(String::length));
Collectors类提供的收集器静态工厂方法
工厂方法 | 返回类型 | 示例 |
---|---|---|
toList | List | toList() |
toSet | Set | toSet() |
toCollection | Collection | toCollection(ArrayList::new) |
counting | Long | counting() |
summingInt | Integer | summingInt(String::length) |
averagingInt | Integer | averagingInt(String::length) |
summarizingInt | IntSummaryStatistics | summarizingInt (String::length) |
joining | String | joining(“, “) |
maxBy | Optional | maxBy((a,b)->a.length()-b.length()) |
mixBy | Optional | mixBy((a,b)->a.length()-b.length()) |
reducing | 归约操作产生的类型 | reducing(0,String::length,Integer::sum) |
collectingAndThen | 转换函数返回的类型 | collectingAndThen(toList(),List::size)) |
groupingBy | Map> | groupingBy(String::length) |
partitioningBy | Map |