个人Stream操作的一些总结(持续更新ing)

过滤出蔬菜
List vegetarian = menu.stream().filter(Dish::isVegetarian)
.collect(Collectors.toList());
过滤出偶数,并且不重复的元素。
List numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
numbers.stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);
截断流
List dishes = menu.stream().filter(d -> d.getCalories() > 300).limit(3)
.collect(toList());
跳过元素
List dishes = menu.stream().filter(d -> d.getCalories() > 300).skip(2)
.collect(toList());
映射
List dishNames = menu.stream().map(Dish::getName).collect(toList());

List words = Arrays.asList(“Java8”, “Lambdas”, “In”, “Action”);
List wordLengths = words.stream() .map(String::length)
.collect(toList());
展开流
List uniqueCharacters = words.stream().map(w -> w.split(“”))
.flatMap(Arrays::stream).distinct().collect(Collectors.toList());
查找和匹配
任意匹配
if(menu.stream().anyMatch(Dish::isVegetarian)){
System.out.println(“The menu is (somewhat) vegetarian friendly!!”);
}
全部匹配
boolean isHealthy = menu.stream().allMatch(d -> d.getCalories() < 1000);
全部不匹配
boolean isHealthy = menu.stream().noneMatch(d -> d.getCalories() >= 1000);
获取任意一个元素
Optional dish =menu.stream() .filter(Dish::isVegetarian) .findAny();
归约
将一个流中的元素反复结合运算得到一个值。
使用循环求和
List numbers = new ArrayList<>();
int sum1 = 0;
for(int x: numbers){
sum1 += x;
}
求和
int sum2 = numbers.stream().reduce(0, (a,b) -> a + b);
int sum3 = menu.stream().map(Dish::getColories).reduce(0, Integer::sum);
求最大值
Optional max = numbers.stream().reduce(Integer::max);
求最小值
Optional min = numbers.stream().reduce(Integer::min);

创建一个流的方法:
1, 使用range方法给定一个范围来创建一个基本类型的流。
IntStream intStream = IntStream.range(1,100);
2,直接给值来创建流
Stream stream = Stream.of(“hanjt”,”is”,”the”,”most”,”dashing”);
3,由数组创建流
IntStream stream2 = Arrays.stream(numbers2);
4, 由文件生成流
try { Stream lines = Files.lines(Paths.get(“data.txt”), Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}
5,由函数生成流
迭代: Stream.iterate(0, n -> n + 2).limit(10) .forEach(System.out::println);
生成:Stream.generate(Math::random).limit(5) .forEach(System.out::println);

猜你喜欢

转载自www.cnblogs.com/JackpotHan/p/9753518.html