Stream介绍
一、Stream介绍
现在有这样的需求:有个菜单list,菜单里面非常多的食物列表,只选取小于400卡路里的并且按照卡路里排序,然后只想知道对应的食物名字。
代码:
package com.cy.java8;
public class Dish {
private final String name;
private final boolean vegetarian;
private final int calories;
private final Type type;
public Dish(String name, boolean vegetarian, int calories, Type type) {
this.name = name;
this.vegetarian = vegetarian;
this.calories = calories;
this.type = type;
}
public String getName() {
return name;
}
public boolean isVegetarian() {
return vegetarian;
}
public int getCalories() {
return calories;
}
public Type getType() {
return type;
}
public enum Type {MEAT, FISH, OTHER}
@Override
public String toString() {
return "Dish{" +
"name='" + name + '\'' +
", vegetarian=" + vegetarian +
", calories=" + calories +
", type=" + type +
'}';
}
}
package com.cy.java8; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors; public class SimpleStream { public static void main(String[] args) {
//have a dish list (menu)
List<Dish> menu = Arrays.asList(
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 300, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH)); List<String> lowerCaloriesDish = getLowerCaloriesDish(menu);
System.out.println(lowerCaloriesDish); List<String> lowerCaloriesDish2 = getLowerCaloriesDish2(menu);
System.out.println(lowerCaloriesDish2);
} /**
* 用Stream的方式去写
*/
private static List<String> getLowerCaloriesDish2(List<Dish> menu){
return menu.stream().filter(dish -> dish.getCalories() < 400)
.sorted(Comparator.comparing(d->d.getCalories()))
.map(Dish::getName)
.collect(Collectors.toList());
} /**
* 以前的写法
* 获取卡路里小于400的食物列表,并且排好序,只返回食物的名字;
* @param menu
* @return
*/
private static List<String> getLowerCaloriesDish(List<Dish> menu){
List<Dish> lowerCalories = new ArrayList<>();
//filter and get calories less 400
for(Dish dish : menu){
if(dish.getCalories() < 400 ){
lowerCalories.add(dish);
}
}
//sort
lowerCalories.sort((o1, o2) -> o1.getCalories() - o2.getCalories()); List<String> lowerCaloreisDishList = new ArrayList<>();
for(Dish dish : lowerCalories){
lowerCaloreisDishList.add(dish.getName());
}
return lowerCaloreisDishList;
}
}
console打印:
[season fruit, prawns, rice]
[season fruit, prawns, rice]
Stream:升级版的api,处理集合等等,有个好处是可以并行处理,而且不需要关心并行处理的细节,
二、Stream的简单用法介绍
围绕着stream的一些方法进行一些代码的举例:
package com.cy.java8; import java.util.*;
import java.util.stream.Stream; public class SimpleStream { public static void main(String[] args) {
//have a dish list (menu)
List<Dish> menu = Arrays.asList(
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 300, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH)); System.out.println("method1 the max calories dish is: " + getMaxCaloriesDish(menu));
System.out.println("method2 the max calories dish is: " + getMaxCaloriesDish2(menu));
System.out.println("have dish calories larger than 600: " + foundDishCaloriesLarger600(menu));
System.out.println("all dish calories larger than 400: " + allDishCaloriesLarger400(menu));
System.out.println("---------------------------------------"); /**
* 创建一个stream
*/
Stream<Dish> stream = Stream.of(new Dish("prawns", false, 300, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH));
stream.forEach(System.out::println);
} /**
* 找出热量最大的食物名字
*/
private static String getMaxCaloriesDish(List<Dish> menu){
return menu.stream().max(Comparator.comparingInt(Dish::getCalories)).get().getName();
} /**
* 找出热量最大的食物,方法二
*/
private static String getMaxCaloriesDish2(List<Dish> menu){
Optional<Dish> maxDish = menu.stream().sorted((d1, d2) -> d2.getCalories() - d1.getCalories()).findFirst();
return maxDish.get().getName();
} /**
* 菜单里面是否有食物热量大于600
*/
private static boolean foundDishCaloriesLarger600(List<Dish> menu){
boolean result = menu.stream().anyMatch(dish -> dish.getCalories() > 600);
return result;
} /**
* 菜单里面食物的热量是否都大于400
*/
private static boolean allDishCaloriesLarger400(List<Dish> menu){
boolean result = menu.stream().allMatch(dish -> dish.getCalories() > 400);
return result;
}
}
打印结果:
method1 the max calories dish is: pork
method2 the max calories dish is: pork
have dish calories larger than 600: true
all dish calories larger than 400: false
---------------------------------------
Dish{name='prawns', vegetarian=false, calories=300, type=FISH}
Dish{name='salmon', vegetarian=false, calories=450, type=FISH}
--
Stream介绍的更多相关文章
- java8学习之Stream介绍与操作方式详解
关于默认方法[default method]的思考: 在上一次[http://www.cnblogs.com/webor2006/p/8259057.html]中对接口的默认方法进行了学习,那在Jav ...
- Java 8 Stream介绍及使用1
(原) stream的内容比较多,先简单看一下它的说明: A sequence of elements supporting sequential and parallel aggregate * o ...
- Spring Cloud Stream介绍-Spring Cloud学习第八天(非原创)
文章大纲 一.什么是Spring Cloud Stream二.Spring Cloud Stream使用介绍三.Spring Cloud Stream使用细节四.参考文章 一.什么是Spring Cl ...
- Java 8 Stream介绍及使用2
(原) stream中另一些比较常用的方法. 1. public static<T> Stream<T> generate(Supplier<T> s) 通过gen ...
- java之stream(jdk8)
一.stream介绍 参考: Java 8 中的 Streams API 详解 Package java.util.stream Java8初体验(二)Stream语法详解 二.例子 im ...
- .NET Core/.NET之Stream简介
之前写了一篇C#装饰模式的文章提到了.NET Core的Stream, 所以这里尽量把Stream介绍全点. (都是书上的内容) .NET Core/.NET的Streams 首先需要知道, Syst ...
- Java进阶篇之十五 ----- JDK1.8的Lambda、Stream和日期的使用详解(很详细)
前言 本篇主要讲述是Java中JDK1.8的一些新语法特性使用,主要是Lambda.Stream和LocalDate日期的一些使用讲解. Lambda Lambda介绍 Lambda 表达式(lamb ...
- java8 Stream常用方法和特性浅析
有一个需求,每次需要将几万条数据从数据库中取出,并根据某些规则,逐条进行业务处理,原本准备批量进行for循环或者使用存储过程,但是for循环对于几万条数据来说效率较低:存储过程因为逻辑非常复杂,写起来 ...
- 完美数据迁移-MongoDB Stream的应用
目录 一.背景介绍 二.常见方案 1. 停机迁移 2. 业务双写 3. 增量迁移 三.Change Stream 介绍 监听的目标 变更事件 四.实现增量迁移 五.后续优化 小结 附参考文档 一.背景 ...
随机推荐
- Xshell6,亲测可用~破解版简单解压免安装~已更新官方版本安装方法
下面的内容别看了,使用这个最新的安装官方版本 https://www.cnblogs.com/taopanfeng/p/11671727.html 下面的内容别看了,使用这个最新的安装官方版本 htt ...
- 从分析攻击方式来谈如何防御DDoS攻击
DDoS攻击的定义: DDoS攻击全称——分布式拒绝服务攻击,是网络攻击中非常常见的攻击方式.在进行攻击的时候,这种方式可以对不同地点的大量计算机进行攻击,进行攻击的时候主要是对攻击的目标发送超过其处 ...
- 为什么现在UML很少用了
新霸哥发现UML在面向对象的设计中的需求,相关行为.一些体系结构的实现提供了一套综合完整的表示法,但是由于使用的人比较少,初学者不容易快速入门,所以就导致了UML不是那么的受欢迎. UML在开发中有什 ...
- 基于zynq XC7Z100 FMC接口通用计算平台 XC7Z100
一.板卡概述 本板卡基于Xilinx公司的FPGA XC7Z100 FFG 9000 芯片, 该平台为设计和验证应用程序提供了一个完整的开发平台.该平台使设计师能够更加简单进行高性能的原型设计,并 ...
- Linux系统账户管理指令
sudo passwd -l weblogic 锁定账户 sudo passwd -u weblogic 解锁账户 useradd weblogic -p xxxxx 添加账户指定密码 sudo us ...
- Registry key 'Software\JavaSoft\Java Runtime Environment\CurrentVersion' has value '1.8', but '1.7'
第一种方法:安装1.8之前安装了1.7,将1.7卸载就好了. 第二种方法:删掉Windows\System32下的java.exe, javaw.exe 就行了,但是安装的1.8的jdk会回到1.7的 ...
- 【HDU3308】LCIS
题目大意:维护一个长度为 N 的序列,支持单点修改,区间查询最长连续上升子序列的长度. 题解: 线段树维护一段区间左端点开始的 LCIS 长度,右端点开始的 LCIS 长度以及区间最优解.考虑进行合并 ...
- 安装python3之后,yum用不了
使用centos 安装python3,并默认python3为python版本之后,用不了yum 原因是yum依赖于python2组件 解决方法: vi /usr/bin/yum 和 vi /usr/l ...
- thinkPHP模型定义
批量新增 ArrayAccess类的属性当做数组访问 插入语句 这段代码说明,User继承的Model类的isupdate属性默认是isupdate,而User::get(1)把这一字段属性更新为tr ...
- 购物网站被p.egou.com强制恶意劫持
今天早上打开电脑浏览京东,发现随便点击商品,都自动转化为淘客推广的页面, 我以为是360浏览器自己干的,然后我换了谷歌,也是一样,难道这是电脑里面有流氓插件? 我又换了火狐,还是一样,没办法了,换IE ...