JDK8之Stream新特性

/***JDK8  Stream特性* Created by chengbx on 2018/5/27.* Java 8 中的 Stream 是对集合(Collection)对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作(aggregate operation),* 或者大批量数据操作 (bulk data operation)。Stream API 借助于同样新出现的 Lambda 表达式,极大的提高编程效率和程序可读性。* 同时它提供串行和并行两种模式进行汇聚操作,并发模式能够充分利用多核处理器的优势,使用 fork/join 并行方式来拆分任务和加速处理过程。* 通常编写并行代码很难而且容易出错, 但使用 Stream API 无需编写一行多线程的代码,就可以很方便地写出高性能的并发程序。* 所以说,Java 8 中首次出现的 java.util.stream 是一个函数式语言+多核时代综合影响的产物。*  一、Stream API 的操作步骤:*        * 1. 创建 Stream** 2. 中间操作** 3. 终止操作(终端操作)** 4.   接口中的默认方法*      接口默认方法的”类优先”原则*      若一个接口中定义了一个默认方法,而另外一个父类或接口中*      又定义了一个同名的方法时*      1.选择父类中的方法。如果一个父类提供了具体的实现,那么*      接口中具有相同名称和参数的默认方法会被忽略.*      2.接口冲突。如果一个父接口提供一个默认方法,而另一个接*      口也提供了一个具有相同名称和参数列表的方法(不管方法*      是否是默认方法),那么必须覆盖该方法来解决冲突* 5.   新增的重复注解@Repeatble和类型注解*         java8新增了重复注解,其使用方式为:@Repeatable(Authorities.class)public @interface Authority {String role();}public @interface Authorities {Authority[] value();}public class RepeatAnnotationUseNewVersion {@Authority(role="Admin")@Authority(role="Manager")publicvoiddoSomeThing(){ }}2.Java8为ElementType枚举增加了TYPE_PARAMETER、TYPE_USE两个枚举值,从而可以使用@Target(ElementType_TYPE_USE)修饰注解定义,这种注解被称为类型注解,可以用在任何使用到类型的地方*/
public class TestStream {List<Employee> employees = Arrays.asList(new Employee("aaa",11,5000),new Employee("bbb",21,5200),new Employee("ccc",13,5500),new Employee("ddd",54,6400),new Employee("eee",16,7100),new Employee("fff",74,7120),new Employee("ggg",12,7150));/*** 创建stream*/@Testpublic void test1(){//1. Collection 提供了两个方法  stream() 与 parallelStream()List<String> list = new ArrayList<>();Stream<String> stream =  list.stream();Stream<String> parallelStream = list.parallelStream(); //获取一个并行流//2. 通过 Arrays 中的 stream() 获取一个数组流Integer[] nums = new Integer[10];Stream<Integer> stream1 = Arrays.stream(nums);//3. 通过 Stream 类中静态方法 of()Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);//4. 创建无限流//迭代Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);stream3.forEach(System.out::println);//生成Stream<Double> stream4 = Stream.generate(Math::random).limit(2);stream4.forEach(System.out::println);}/*筛选与切片filter——接收 Lambda , 从流中排除某些元素。limit——截断流,使其元素不超过给定数量。skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素*///内部迭代:迭代操作 Stream API 内部完成
    @Testpublic void test2(){//中间操作,不会执行任何操作Stream<Employee> str = employees.stream().filter((e) -> e.getAge()>30).limit(1);//终止操作,一次性执行全部内容,即"惰性求值"
        str.forEach(System.out::println);// employees.stream().filter((e) -> e.getAge()<30)//            .forEach((employee) -> System.out.println(employee));
    }//外部迭代
    @Testpublic void test3(){Iterator<Employee> it = employees.iterator();while(it.hasNext()){System.out.println(it.next());}}@Testpublic void test4(){employees.stream().filter((e) -> {System.out.println("短路!"); // &&  ||return e.getSalary() >= 5000;}).limit(3).forEach(System.out::println);}@Testpublic void test5(){employees.parallelStream().filter((e) -> e.getSalary() >= 5000).skip(2).forEach(System.out::println);}@Testpublic void test6(){employees.stream().distinct().forEach(System.out::println);}/*** 映射* map -接收lambda,将元素转换成其他形式获取信息,接收一个函数作为参数,该函数会被应用在每个元素上,并将其映射成一个新的元素。* flatmap-接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流*/@Testpublic void test7(){List<String> list = Arrays.asList("aaa","bbb","ccc","ddd");list.stream().map((str) -> str.toUpperCase()).forEach((str) -> System.out.println(str));System.out.println("---------------");employees.stream().map(Employee::getName).forEach((name) ->System.out.println(name));}/*** 排序* sorted()--自然排序(comparable)* sorted(Comparator com)--定制排序(Comparator)*/@Testpublic void test8(){List<String> list = Arrays.asList("eee","ggg","ccc","ddd");list.stream().sorted().forEach(System.out::println);System.out.println("-------------------以下是定制排序-------------");employees.stream().sorted((e1,e2) ->{if (e1.getAge() ==e2.getAge()) {return e1.getName().compareTo(e2.getName());}else{return Integer.compare(e1.getAge(),e2.getAge());}}).forEach((employee) -> System.out.println(employee));}//3. 终止操作/*allMatch——检查是否匹配所有元素anyMatch——检查是否至少匹配一个元素noneMatch——检查是否没有匹配的元素findFirst——返回第一个元素findAny——返回当前流中的任意元素count——返回流中元素的总个数max——返回流中最大值min——返回流中最小值注意:流进行了终止操作后,不能再次使用*/@Testpublic void test9(){boolean b = employees.stream().allMatch((emp) -> emp.getAge()==15);System.out.println(b);System.out.println("---------------");boolean b1 = employees.stream().anyMatch((emp) -> emp.getAge()==15);System.out.println(b1);System.out.println("---------------");boolean b2 = employees.stream().noneMatch((emp) -> emp.getAge()==15);System.out.println(b2);System.out.println("---------------");Optional<Employee> optional = employees.stream().sorted((emp1, emp2) -> Double.compare(emp1.getSalary(),emp2.getSalary())).findFirst();System.out.println(optional.get());System.out.println("---------------");Optional<Employee> optional1 = employees.parallelStream().filter((emp) -> emp.getAge() >15).findAny();System.out.println(optional1);System.out.println("---------------");Long count = employees.parallelStream().filter((emp) -> emp.getAge() >15).count();System.out.println(count);Optional<Double> optiona3 = employees.stream().map((emp) -> emp.getSalary()).max(Double::compareTo);System.out.println(optiona3.get());System.out.println("---------------");Optional<Employee> optiona4 = employees.stream().min((e1,e2) ->Double.compare(e1.getSalary(),e2.getSalary()));System.out.println(optiona4);}/*** 归约reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。*/@Testpublic void test10(){List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);Integer sum = list.stream().reduce(0,(x,y) -> x+y);System.out.println(sum);//55System.out.println("---------------------");Optional<Double> sumSal = employees.stream().map(Employee::getSalary).reduce(Double::sum);System.out.println(sumSal);}/*** 收集:* collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法*///将employee集合中name值取出来放入集合中 aaa bbb ccc ddd eee fff ggg
    @Testpublic void test11(){List list = employees.stream().map(Employee::getName).collect(Collectors.toList());list.forEach(System.out::println);}@Testpublic void test12(){Set set = employees.stream().map(Employee::getName).collect(Collectors.toSet());set.forEach(System.out::println);}@Testpublic void test13(){HashSet hashSet = employees.stream().map(Employee::getName).collect(Collectors.toCollection(HashSet::new));hashSet.forEach(System.out::println);}//获取集合中元素的个数  7
    @Testpublic void test14(){long count =  employees.stream().collect(Collectors.counting());System.out.println(count);System.out.println("----------------");//获取工资平均值Double avgMoney = employees.stream().collect(Collectors.averagingDouble((emp) -> emp.getSalary()));System.out.println(avgMoney);//6210.0System.out.println("----------------");//工资总和Double sumMoney = employees.stream().collect(Collectors.summingDouble(Employee::getSalary));System.out.println(sumMoney);//最大值Optional<Employee> optional= employees.stream().collect(Collectors.maxBy((emp1,emp2) -> Double.compare(emp1.getSalary(),emp2.getSalary())));System.out.println(optional.get());//Employee{name='ggg', age=12, salary=7150.0}//最小值Optional<Double> minMoney = employees.stream().map(Employee::getSalary).collect(Collectors.minBy(Double::compare));System.out.println(minMoney.get());}//分组
    @Testpublic void test15(){employees.stream().collect(Collectors.groupingBy(Employee::getAge));}//分区
    @Testpublic  void test16(){Map<Boolean,List<Employee>> map =employees.stream().collect(Collectors.partitioningBy((e) -> e.getSalary() >6000));System.out.println(map);//{false=[Employee{name='aaa', age=11, salary=5000.0}, Employee{name='bbb', age=21, salary=5200.0},// Employee{name='ccc', age=13, salary=5500.0}],// true=[Employee{name='ddd', age=54, salary=6400.0}, Employee{name='eee', age=16, salary=7100.0},// Employee{name='fff', age=74, salary=7120.0}, Employee{name='ggg', age=12, salary=7150.0}]}
}@Testpublic void test17(){DoubleSummaryStatistics dss =employees.stream().collect(Collectors.summarizingDouble(Employee::getSalary));//求平均值
        System.out.println(dss.getAverage());//求最大值
        System.out.println(dss.getMax());//求和
        System.out.println(dss.getSum());}    @Testpublic void test18(){String name = employees.stream().map(Employee::getName).collect(Collectors.joining(","));System.out.println(name);//aaa,bbb,ccc,ddd,eee,fff,ggg
    }
}

 

转载于:https://www.cnblogs.com/cbxBlog/p/9123106.html

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

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

相关文章

鸡蛋学运维-2:Rsync同步配置步骤

说明&#xff1a;系统环境CentOS release 6.5 (Final) 2.6.32-431.el6.x86_64rsync server:配置步骤1、vi /etc/rsyncd.conf#Rsync server#created by lijianfeng 18:26 2017-9-24#rsyncd.conf start#uid rsyncgid rsyncuse chroot nomax connections 2000timeout 600pid…

IntelliJ IDEA代码分屏显示

转载于:https://www.cnblogs.com/EasonJim/p/9124809.html

vscode重置应用程序_如何在Windows 10上重置应用程序的数据

vscode重置应用程序With Windows 10’s Anniversary Update, you can now reset an app’s data without actually uninstalling and reinstalling the app. This can fix problems when an app has gotten into a bad state, or just quickly restore an app to its default s…

程序报错与提示

2019独角兽企业重金招聘Python工程师标准>>> 我们在开发中, 为了程序的规范性,把报错级别,调的比较高NOTICE级别的也报出来,有助于我们快速定位错误和代码规范&#xff0c;但是,在产品上线后,网站运营过程中,就不宜报这么多错. 1:这种错误给客户的印象不好 2:在报错…

【codevs1230】元素查找

problem 给出n个正整数&#xff0c;然后有m个询问询问该整数是否在n个正整数中出现过solution 哈希表&#xff1f; 当然是set水洛 codes #include<iostream> #include<set> using namespace std; set<int>s; int main(){int n, m;cin>>n>>m;for…

dock怎么自定义_如何自定义和调整Mac的Dock

dock怎么自定义The macOS dock normally appears at the bottom of your screen, but it doesn’t have to. The dock is customizable in quite a few ways you might not be aware of, especially if you’re a new Mac user. macOS坞站通常显示在屏幕底部&#xff0c;但不是…

ios 轻扫手势_轻扫即可快速删除iOS计算器中的数字

ios 轻扫手势iOS’ built-in calculator is a basic, simple-to-use calculator that’s very handy for doing some quick calculations, such as calculating the tip on your restaurant bill. It’s also useful for longer, more complicated calculations. However, ther…

游戏安全资讯精选 2017年第十期 英国彩票网遭遇DDoS攻击,中断90分钟 DNSMASQ多高危漏洞公告 阿里云协助警方破获国内最大黑客攻击案,攻击峰值690G...

【本周游戏行业DDoS攻击态势】 国庆期间&#xff0c;针对游戏行业的DDoS攻击放缓&#xff0c;攻击者也在放“小长假”&#xff0c;10月8日超过500G的攻击可视作攻击猛烈度恢复的表现。 【游戏安全动态】 英国彩票网遭遇DDoS攻击&#xff0c;中断90分钟 点击查看原文 点评&#…

02 jmeter 简单发送http请求

一、新建http请求模板1、测试计划2、右键Threads(users)-线程组3、右键sample-http请求4、右键监听器-查看结果树5、右键监听器-查看聚合报告二、编辑http请求内容三、设置并发用户1&#xff1a;虚拟用户数&#xff1b; 2&#xff1a;加载用户时间&#xff1b;3、每个用户循环次…

java调用siri 语言_如何更改Siri的声音,口音,性别和语言

java调用siri 语言Most of us are familiar with Siri as an American female voice. What you may not realize is that you can actually change Siri to have a different accent, gender, and language. 我们大多数人都熟悉Siri&#xff0c;这是一种美国女性声音。 您可能没…

高手与菜鸟,思想与技术

这是个严肃的话题。同样的问题&#xff0c;高手和菜鸟的看法是不同&#xff0c;怎么样不同呢&#xff1f;我们是高手还菜鸟呢&#xff1f;看看以下问题&#xff1a;对于AJAX&#xff1a;菜鸟看到的是一种新技术&#xff0c;趋之若骛&#xff1b;高手看到的是javascript的一种巧…

玩转 React(四)- 创造一个新的 HTML 标签

在第二篇文章 《新型前端开发方式》 中有说到 React 有很爽的一点就是给我们一种创造 HTML 标签的能力&#xff0c;那么今天这篇文章就详细讲解下 React 是如何提供这种能力的&#xff0c;作为前端开发者如何来运用这种能力。 在第三篇文章 《JavaScript代码里写HTML一样可以很…

mac word 设置语言_如何更改Mac的语言和区域设置

mac word 设置语言If you want to use your Mac in a different language, or you’re live in a different region, then you can change it in OS X. When you do, it’ll display everything in your preferred language, currency, date format, and more. 如果您想以其他语…

【Luogu3931】SAC E#1 - 一道难题 Tree

problem solution codes //树形DP //f[u]:割掉u和u子树中所有的叶子节点所需要的最小代价 #include<iostream> #include<vector>using namespace std; typedef long long LL; const int N (int)1e510, inf 1e9;int n, S;struct node{LL to, v;node(LL to, LL v):…

IT史上十大收购案

本文讲的是IT史上十大收购案【IT168 资讯】据英国资讯网站V3报道&#xff0c;本周&#xff0c;业界中的大事件无疑是硬件巨头Intel公司斥资76.8亿美元全盘收购著名安全软件公司McAfee。本次收购被看做是软硬件领域的一次亲密接触&#xff0c;下面为大家盘点近年来IT领域中影响较…

飞利浦dicom_如何按计划打开或关闭飞利浦色相灯

飞利浦dicomThe Philips Hue app can do a handful of cool stuff with your Hue lights, including the ability to schedule your lights to turn on and off at specific times throughout the day. Here’s how to set it up so that you never have to flip a switch ever…

Mono生命周期小实验

今天在写代码的时候&#xff0c;遇到一个初始化顺序问题&#xff0c;于是做了一个实验&#xff0c;下面记录结果&#xff1a; 情景&#xff1a; 1.在 脚本A中实例化 一个预制体&#xff0c;该预制体挂有脚本B 2.在 脚本A中&#xff0c;获取实例化物体 身上的 脚本B&#xff0c;…

[读书笔记]大型分布式网站架构设计与实践.分布式缓存

前言&#xff1a;本书是对分布式系统架构涉及到的相关技术的一本科普书籍。由于很难作为开发参考&#xff0c;只能但求了解。所以通篇浅读&#xff0c;对分布式系统进行大致的了解。因为写的非常好&#xff0c;感觉非常有意思&#xff0c;自己也做不出总结。所谓的读书笔记也就…

宁波保哥后院_如何抛出终极后院电影之夜

宁波保哥后院Most people have the basics of throwing a movie night down: you get a movie, you get snacks, you get comfortable, and boom, you’re done. When it comes to throwing a movie party in the backyard, however, things get a little trickier. Read on as…

大厂前端高频面试问题与答案精选

近日&#xff0c;GitHub上一位名为木易杨&#xff08;yygmind&#xff09;的开发者&#xff0c;在 GitHub 中建了一个名为Advanced-Frontend/Daily-Interview-Question项目&#xff0c;该项目每天会更新一道前端大厂面试题&#xff0c;并邀请开发者在issue区中作答&#xff0c;…