标签:for util obj average code 引入 count() option 扁平化
import java.util.Arrays;
import java.util.List;
import java.util.OptionalInt;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* 数值流
*/
public class MapDemo3 {
public static void main(String[] args){
List<Apple> appleList = Arrays.asList(new Apple("red",12),new Apple("yellow",15),new Apple("green",10),new Apple("red",10));
//映射到数值流
//IntStream还支持其他的方便方法,如max、min、average等。
int sumWeight = appleList.stream()
.mapToInt(Apple::getWeight)
.sum();
System.out.println(sumWeight);
//原始流转换成一般流
IntStream intStream = appleList.stream()
.mapToInt(Apple::getWeight);//将 Stream 转 换为数值流
Stream<Integer> boxed = intStream.boxed();//将数值流转 换为Stream
//默认值OptionalInt
OptionalInt optionalInt = appleList.stream()
.mapToInt(Apple::getWeight)
.max();
int max = optionalInt.orElse(-1);
System.out.println(max);//如果没有最大值的话,显式提供一个默认最大值
//数值范围
//Java 8引入了两个可以用于IntStream和LongStream的静态方法,帮助生成这种范围: range和rangeClosed。这两个方法都是第一个参数接受起始值,第二个参数接受结束值。但 range是不包含结束值的,而rangeClosed则包含结束值
IntStream intStream1 = IntStream.rangeClosed(1, 100)
.filter(n -> n % 2 == 0);
System.out.println(intStream1.count());//从1到100 偶数个数
}
}
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* 勾股数
*/
public class MapDemo4 {
public static void main(String[] args) {
Stream<double[]> pythagoreanTriples = IntStream.rangeClosed(1, 100)//从rangeClosed返回的IntStream生成一个IntStream
.boxed()//生成Stream<Integer>
.flatMap(a -> //flatMap把所有生成的三元数流扁平化成一个流
IntStream.rangeClosed(a, 100)
.mapToObj(b -> new double[]{a, b, Math.sqrt(a * a + b * b)})//返回一个对象值流
.filter(t -> t[2] % 1 == 0));//元组中的第三个元素必须是整数
pythagoreanTriples.limit(5) //明确限定从生成的流 中要返回多少组勾股数
.forEach(t->System.out.println(t[0] + ", " + t[1] + ", " + t[2]));
//3.0, 4.0, 5.0
//5.0, 12.0, 13.0
//6.0, 8.0, 10.0
//7.0, 24.0, 25.0
//8.0, 15.0, 17.0
}
}
标签:for util obj average code 引入 count() option 扁平化
原文地址:https://www.cnblogs.com/fly-book/p/12651372.html