Predicate
Function
Consumer
filter返回boolean
map 接收和筛选结果类型相同
distinct删除重复
limit
skip跳过
collect(toList(),toSet())
流扁平化
flatMap(Arrays::stream())接收一个数组(每个数组再转换成对应的流,最后合并成一个流),并返回对应的一个流(2个-2个)(字符流)
短路求值
allMatch
anyMatch
noneMatch
findFirst
findAny
归约reduce
reduce(joining())
int sum=numbers.stream().reduce(0,(a,b)->a+b);
//+-*/
流的转换
int calories = menu.stream()
.mapToInt(Dish::getCalories)
.sum();
IntStream ->mapToInt
Stream ->boxed()
IntStream intStream=m.stream().mapToInt(D::getV);
Stream<Integer> stream=intStream.boxed();
max,min,初始值为0,不知道是否是正确的最大值,求和初始值为0,可直接使用
OptionalInt maxCalories = menu.stream().mapToInt(Dish::getCalories).max();
int max = maxCalories.orElse(1);
range(不含) ,rangeClose(含100
IntStream evenNumbers = IntStream.rangeClosed(1, 100)
.filter(n -> n % 2 == 0);
System.out.println(evenNumbers.count());
Stream.of创建字符串流 Stream.empty()
Stream<String> stream = Stream.of("Java 8 ", "Lambdas ", "In ", "Action");
你可以使用静态方法Arrays.stream从数组创建一个流。它接受一个数组作为参数。例如,
你可以将一个原始类型int的数组转换成一个IntStream,如下所示:
int[] numbers = {2, 3, 5, 7, 11, 13};
int sum = Arrays.stream(numbers).sum();
文件流 106
无限流
Stream.iterate(0, n -> n + 2)
.limit(10)
.forEach(System.out::println);
汇总
//总卡路里,collect
int totalValue=transactions.stream().collect(summingInt(Transaction::getValue));
类似averagingInt
//汇总
IntSummaryStatistics intSummaryStatistics = transactions.stream().collect(summarizingInt(Transaction::getValue));
结果
类似 summarizingInt,summarizinglong,summarizingdouble
连接字符串
String tradersFrom=transactions.parallelStream()
.map(transaction -> transaction.getTrader().getName())
.distinct()
.sorted()
.collect(joining());
若已存在toString方法,可不用提取数据直接用
分组
Map<Dish.Type,Map<CaloriesLevel,List<Dish>>> dishesByType=menu.stream()
.collect(groupingBy(Dish::getType
,groupingBy(dish->{
if(dish.getCalories()<400) return CaloriesLevel.D;
else if (dish.getCalories()>400&&dish.getCalories()<700) return CaloriesLevel.N;
else return CaloriesLevel.F;
})));
注意,普通的单参数groupingBy(f)(其中f是分类函数)实际上是groupingBy(f,
toList())的简便写法。
Map<Dish.Type,Long> typeCount=menu.stream().collect(groupingBy(Dish::getType,counting()));
System.out.println(typeCount);
在需要将数值范围装箱成为一个一般流时,boxed尤其有用
IntStream intStream = menu.stream().mapToInt(Dish::getCalories);
Stream<Integer> stream = intStream.boxed();