Java 8 Stream API示例

您好朋友,在本文中,我们将讨论Java 8 Stream API示例。

因此,我们要做的是,创建一个Player类,创建Player类的多个对象,然后创建一个测试类,在其中使用Stream API检索播放器的数据。

第一个例子是普通流(我们可以称之为串行流),第二个例子是并行流。

流API

串行流

第一步,让我们创建一个Player类。

public class Player {private String name;private int id;private int fees;private String grade;public Player(String name, int id, int fees, String grade) {super();this.name = name;this.id = id;this.fees = fees;this.grade = grade;}/*** @return the name*/public String getName() {return name;}/*** @param name the name to set*/public void setName(String name) {this.name = name;}/*** @return the id*/public int getId() {return id;}/*** @param id the id to set*/public void setId(int id) {this.id = id;}/*** @return the fees*/public int getFees() {return fees;}/*** @param fees the fees to set*/public void setFees(int fees) {this.fees = fees;}/*** @return the grade*/public String getGrade() {return grade;}/*** @param grade the grade to set*/public void setGrade(String grade) {this.grade = grade;}@Overridepublic String toString() {return "Player [name=" + name + ", id=" + id + ", fees=" + fees + ", grade=" + grade + "]";}
}

现在,让我们创建一个测试类来测试Stream API。

public class TestJava8Streams {public static void main(String[] args) {List players = createPlayerList();/**********STREAM****************/System.out.println("STREAM");/****Get List of Players Who are in Grade AA***/System.out.println("Grade AA Players :");players.stream().filter((Player player1)-> player1.getGrade().equalsIgnoreCase("AA")).collect(Collectors.toList()).forEach(System.out::println);/*********************************************/	/********Get Fee of Grade AA Players**********/System.out.println("Fee Grade AA Players :");players.stream().filter((Player player1)-> player1.getGrade().equalsIgnoreCase("AA")).map(p->p.getFees()).collect(Collectors.toList()).forEach(System.out::println);;/*********************************************//********Are All players getting Match Fee of more than 3 Crore*****/System.out.println("Does All Players getting Match Fee of more than 3 Crores:");boolean isAllPlayerHavingFeeMoreThansThreeCrore1 = players.stream().allMatch(player1 -> player1.getFees()>=30000000);System.out.println(isAllPlayerHavingFeeMoreThansThreeCrore1 ? "Yes": "No");/*******************************************************************//********Are All players getting Match Fee of more than 1 Crore*****/System.out.println("Does All Players getting Match Fee equal to or more than 1 Crore:");boolean isAllPlayerHavingFeeMoreThansOneCrore1 = players.stream().allMatch(player1 -> player1.getFees()>=10000000);System.out.println(isAllPlayerHavingFeeMoreThansOneCrore1 ? "Yes": "No");/*******************************************************************//*************Get Players with their Name and Grade******************/players.stream().collect(Collectors.toMap((Player player1)-> player1.getName(), (Player player1)-> player1.getGrade()));players.forEach(player1 -> System.out.println("Player Name:"+player1.getName() + " | " + "Player Grade:"+player1.getGrade()));/*******************************************************************//*************Get any player detail.As per java docs ,multiple invocations can return different results******/Optional player1 =players.stream().findAny();System.out.println("Any Player:"+player1.get());/*******************************************************************//********Get First Player in the list*****/players.stream().findFirst().get().getName();System.out.println("First Player in the list:"+player1.get());/****************************************//********Get First Two Players from the list******/System.out.println("First two Players in the list:");players.stream().limit(2).collect(Collectors.toList()).forEach(System.out::println);;/************************************************//********Player whose name alphabetically comes Last in the list******/Optional alphabeticallyLast1 = players.stream().max((Player st1,Player st2)-> st1.getName().compareToIgnoreCase(st2.getName()));System.out.println("Alphabetically last Player:"+alphabeticallyLast1.get().getName());/************************************************//********Player whose name alphabetically comes First in the list******/Optional alphabeticallyFirst1 = players.stream().min((Player st1,Player st2)-> st1.getName().compareToIgnoreCase(st2.getName()));System.out.println("Alphabetically first Player::"+alphabeticallyFirst1.get().getName());/**********************************************************************/}private static List createPlayerList(){List palyers = new ArrayList();Player player2 = new Player("Dhawan",101,70000000,"AA");Player player1 = new Player("Rohit",102,70000000,"AA");Player player3 = new Player("Rahane",201,50000000,"A");Player player4 = new Player("Dhoni",202,50000000,"A");Player player5 = new Player("Raina",301,10000000,"C");Player player6 = new Player("Kohli",302,70000000,"AA");Player player7 = new Player("Jadeja",401,50000000,"A");Player player8 = new Player("Bumrah",402,70000000,"AA");Player player9 = new Player("Umesh",403,30000000,"B");Player player10 = new Player("Karthik",404,30000000,"B");Player player11 = new Player("Pandey",405,10000000,"C");palyers.add(player1);palyers.add(player2);palyers.add(player3);palyers.add(player4);palyers.add(player5);palyers.add(player6);palyers.add(player7);palyers.add(player8);palyers.add(player9);palyers.add(player10);palyers.add(player11);return palyers;}
}

输出是:

Grade AA Players :Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]Player [name=Dhawan, id=101, fees=70000000, grade=AA, addresses=null]Player [name=Kohli, id=302, fees=70000000, grade=AA, addresses=null]Player [name=Bumrah, id=402, fees=70000000, grade=AA, addresses=null]Fee Grade AA Players :70000000700000007000000070000000Does All Players getting Match Fee of more than 3 Crores:falseDoes All Players getting Match Fee equal to or more than 1 Crore:truePlayer Name:Rohit | Player Grade:AAPlayer Name:Dhawan | Player Grade:AAPlayer Name:Rahane | Player Grade:APlayer Name:Dhoni | Player Grade:APlayer Name:Raina | Player Grade:CPlayer Name:Kohli | Player Grade:AAPlayer Name:Jadeja | Player Grade:APlayer Name:Bumrah | Player Grade:AAPlayer Name:Umesh | Player Grade:BPlayer Name:Karthik | Player Grade:BPlayer Name:Pandey | Player Grade:CAny Player:Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]First Player in the list:Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]First two Players in the list:Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]Player [name=Dhawan, id=101, fees=70000000, grade=AA, addresses=null]Sorted List of PLayers according to their name in Alphabetical order:Player [name=Bumrah, id=402, fees=70000000, grade=AA, addresses=null]Player [name=Dhawan, id=101, fees=70000000, grade=AA, addresses=null]Player [name=Dhoni, id=202, fees=50000000, grade=A, addresses=null]Player [name=Jadeja, id=401, fees=50000000, grade=A, addresses=null]Player [name=Karthik, id=404, fees=30000000, grade=B, addresses=null]Player [name=Kohli, id=302, fees=70000000, grade=AA, addresses=null]Player [name=Pandey, id=405, fees=10000000, grade=C, addresses=null]Player [name=Rahane, id=201, fees=50000000, grade=A, addresses=null]Player [name=Raina, id=301, fees=10000000, grade=C, addresses=null]Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]Player [name=Umesh, id=403, fees=30000000, grade=B, addresses=null]Alphabetically last Player:UmeshAlphabetically first Player::Bumrah

并行流

以下是使用并行流的相同示例

下面的代码是完全一样的,除了我们将调用parallelStream()方法而不是stream()方法。

public class TestJava8ParallelStream {public static void main(String[] args) {List players = createPlayerList();/****PARALLEL STREAM****************/System.out.println("PARALLEL STREAM");/****Get List of Players Who are in Grade AA***/System.out.println("Grade AA Players :");players.parallelStream().filter((Player player1)-> player1.getGrade().equalsIgnoreCase("AA")).collect(Collectors.toList()).forEach(System.out::println);/*********************************************/	/********Get Fee of Grade AA Players**********/System.out.println("Fee Grade AA Players :");players.parallelStream().filter((Player player1)-> player1.getGrade().equalsIgnoreCase("AA")).map(p->p.getFees()).collect(Collectors.toList()).forEach(System.out::println);;/*********************************************//********Are All players getting Match Fee of more than 3 Crore*****/System.out.println("Does All Players getting Match Fee of more than 3 Crores:");boolean isAllPlayerHavingFeeMoreThansThreeCrore1 = players.parallelStream().allMatch(player1 -> player1.getFees()>=30000000);System.out.println(isAllPlayerHavingFeeMoreThansThreeCrore1 ? "Yes": "No");/*******************************************************************//********Are All players getting Match Fee of more than 1 Crore*****/System.out.println("Does All Players getting Match Fee equal to or more than 1 Crore:");boolean isAllPlayerHavingFeeMoreThansOneCrore1 = players.parallelStream().allMatch(player1 -> player1.getFees()>=10000000);System.out.println(isAllPlayerHavingFeeMoreThansOneCrore1 ? "Yes": "No");/*******************************************************************//*************Get Players with their Name and Grade******************/players.parallelStream().collect(Collectors.toMap((Player player1)-> player1.getName(), (Player player1)-> player1.getGrade()));players.forEach(player1 -> System.out.println("Player Name:"+player1.getName() + " | " + "Player Grade:"+player1.getGrade()));/*******************************************************************//*************Get any player detail.As per java docs ,multiple invocations can return different results******/Optional player1 =players.parallelStream().findAny();System.out.println("Any Player:"+player1.get());/*******************************************************************//********Get First Player in the list*****/players.parallelStream().findFirst().get().getName();System.out.println("First Player in the list:"+player1.get());/****************************************//********Get First Two Players from the list******/System.out.println("First two Players in the list:");players.parallelStream().limit(2).collect(Collectors.toList()).forEach(System.out::println);;/************************************************//********Player whose name alphabetically comes Last in the list******/Optional alphabeticallyLast1 = players.parallelStream().max((Player st1,Player st2)-> st1.getName().compareToIgnoreCase(st2.getName()));System.out.println("Alphabetically last Player:"+alphabeticallyLast1.get().getName());/************************************************//********Player whose name alphabetically comes First in the list******/Optional alphabeticallyFirst1 = players.parallelStream().min((Player st1,Player st2)-> st1.getName().compareToIgnoreCase(st2.getName()));System.out.println("Alphabetically first Player::"+alphabeticallyFirst1.get().getName());/**********************************************************************/}private static List createPlayerList(){List palyers = new ArrayList();Player player2 = new Player("Dhawan",101,70000000,"AA");Player player1 = new Player("Rohit",102,70000000,"AA");Player player3 = new Player("Rahane",201,50000000,"A");Player player4 = new Player("Dhoni",202,50000000,"A");Player player5 = new Player("Raina",301,10000000,"C");Player player6 = new Player("Kohli",302,70000000,"AA");Player player7 = new Player("Jadeja",401,50000000,"A");Player player8 = new Player("Bumrah",402,70000000,"AA");Player player9 = new Player("Umesh",403,30000000,"B");Player player10 = new Player("Karthik",404,30000000,"B");Player player11 = new Player("Pandey",405,10000000,"C");palyers.add(player1);palyers.add(player2);palyers.add(player3);palyers.add(player4);palyers.add(player5);palyers.add(player6);palyers.add(player7);palyers.add(player8);palyers.add(player9);palyers.add(player10);palyers.add(player11);return palyers;}
}

这是带有并行流的输出:

Grade AA Players :Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]Player [name=Dhawan, id=101, fees=70000000, grade=AA, addresses=null]Player [name=Kohli, id=302, fees=70000000, grade=AA, addresses=null]Player [name=Bumrah, id=402, fees=70000000, grade=AA, addresses=null]Fee Grade AA Players :70000000700000007000000070000000Does All Players getting Match Fee of more than 3 Crores:falseDoes All Players getting Match Fee equal to or more than 1 Crore:truePlayer Name:Rohit | Player Grade:AAPlayer Name:Dhawan | Player Grade:AAPlayer Name:Rahane | Player Grade:APlayer Name:Dhoni | Player Grade:APlayer Name:Raina | Player Grade:CPlayer Name:Kohli | Player Grade:AAPlayer Name:Jadeja | Player Grade:APlayer Name:Bumrah | Player Grade:AAPlayer Name:Umesh | Player Grade:BPlayer Name:Karthik | Player Grade:BPlayer Name:Pandey | Player Grade:CAny Player:Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]First Player in the list:Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]First two Players in the list:Player [name=Rohit, id=102, fees=70000000, grade=AA, addresses=null]Player [name=Dhawan, id=101, fees=70000000, grade=AA, addresses=null]Alphabetically last Player:UmeshAlphabetically first Player::Bumrah

以上就是Java 8 Stream API示例。 如果发现有帮助,请与您分享对您有帮助的人。

翻译自: https://www.javacodegeeks.com/2018/07/java-8-stream-api-examples.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/345730.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

概率密度函数、概率分布函数、常见概率分布

1. 概率函数 概率函数,就是用函数的形式来表达概率。 piP(Xai)(i1,2,3,4,5,6)p_iP(Xa_i)(i1,2,3,4,5,6)pi​P(Xai​)(i1,2,3,4,5,6) 在这个函数里,自变量(X)是随机变量的取值,因变量(pip_ipi​&#xff09…

Moment Generating Function

1. 概率统计中的“矩”是什么? 对比物理的力矩,你会发现,概率论中的“矩”真的是很有启发性的一个词。 1.1 力矩 大家应该都知道物理中的力矩,我这里也不展开说细节了,用一幅图来帮助大家回忆一下: 1.…

Lyapunov and Stability Theory

一、什么是稳定点 一个控制系统就和一个社会一样,稳定性是首先要解决的重要问题,是其他一切工作的基础。稳定性问题的字面意思很好理解了,那就是系统在受到扰动后,能否能有能力在平衡态继续工作。大家都知道,历史上社…

对采样的理解

1. 什么是采样 我们知道了一个变量的分布,要生成一批服从这个分布的样本,这个过程就叫采样。 听起来好像很简单,对一些简单的分布函数确实如此,比如,均匀分布、正太分布,但只要分布函数稍微复杂一点&#…

如何避免Java线程中的死锁?

如何避免Java死锁? 是Java面试中最受欢迎的问题之一,也是本季多线程的风格,主要是在高层提出,并带有很多后续问题。 尽管问题看起来很基础,但是一旦您开始深入研究,大多数Java开发人员就会陷入困境。 面试…

Approximation and fitting、Statistical estimation

一、Approximation and fitting 1. 拟合与回归的区别 回归分析:是一种统计学上分析数据的方法,目的在于了解两个或多个变量间是否相关、相关方向与强度,并建立数学模型以便观察特定变量来预测研究者感兴趣的变量。 拟合:是一种把…

Probability(概率) vs Likelihood(似然)

1. 先验概率,条件概率与后验概率 2. Probability(概率) vs Likelihood(似然) Probabiity(概率):给定某一参数值,求某一结果的可能性 Likelihood(似然):给定某一结果,求某…

线性回归 逻辑回归

分类就是到底是1类别还是0类别。 回归就是预测的不是一个类别的值,而是一个具体的值,具体借给你多少钱哪? 一、回归分析 回归分析(英语:Regression Analysis)是一种统计学上分析数据的方法,目…

rmi full gc问题_RMI强制Full GC每小时运行一次

rmi full gc问题在我职业生涯中进行的所有故障排除练习中,我都感觉到,随着时间的推移,我所追寻的错误在不断演变,变得越来越卑鄙和丑陋。 也许仅仅是我的年龄开始了。这个特别的Heisenbug –看起来像这篇帖子一样,再次…

联邦学习 Federated Learning

应该很多人听过但是始终都没懂啥是联邦学习?百度一下发现大篇文章都说可以用来解决数据孤岛,那它又是如何来解决数据孤岛问题的? 1、联邦学习的背景介绍 近年来人工智能可谓风风火火,掀起一波又一波浪潮,从人脸识别、…

优化器算法Optimizer详解(BGD、SGD、MBGD、Momentum、NAG、Adagrad、Adadelta、RMSprop、Adam)

本文将梳理: 每个算法的梯度更新规则和缺点 为了应对这个不足而提出的下一个算法 超参数的一般设定值 几种算法的效果比较 选择哪种算法 0.梯度下降法深入理解 以下为个人总结,如有错误之处,各位前辈请指出。 对于优化算法,优化…

gradle构建_指定Gradle构建属性

gradle构建属性是用于轻松自定义Gradle构建和Gradle环境的宝贵工具。 我将在本文中演示一些用于指定Gradle构建中使用的属性的方法。 Gradle支持项目属性和系统属性 。 这篇文章中有趣的是两者之间的主要区别是如何访问它们。 项目属性更有助于按名称直接访问,而系…

线性代数之——行列式及其性质

https://zhuanlan.zhihu.com/p/50912180

Cauchy-Schwarz不等式

1. Cauchy不等式 ##2. 推广:HolderH\ddot{o}lderHolder不等式 3. Cauchy-Schwarz不等式 结论:任意两个向量的内积(点乘)的模平方,必定小于或等于这两个向量各自的模的乘积。 https://www.jianshu.com/p/77f9607d88d…

StevenBoyd--Convex optimization--0. Contents-catalog

把自己最近学习的Steven Boyd的convex optimization的内容整理一下,将思维导图发出来供自己学习及参考。

串行内存消耗 并行内存_如何估算内存消耗?

串行内存消耗 并行内存这个故事可以追溯到至少十年之前,当时我第一次接触PHB时遇到一个问题:“在生产部署中,我们需要购买多大服务器”。 我们正在构建的新的,闪亮的系统距离生产开始还有9个月的时间,显然该公司已承诺…