import lombok.Getter;
import lombok.Setter; @Setter
@Getter
public class Person {
private String name; // 姓名
private int salary; // 薪资
private int age; // 年龄
private String sex; //性别
private String area; // 地区 // 构造方法
public Person(String name, int salary, int age,String sex,String area) {
this.name = name;
this.salary = salary;
this.age = age;
this.sex = sex;
this.area = area;
}
}
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream; @Slf4j
public class StreamTest {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1,6,6,8);
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Tom", 8900, 23, "male", "New York"));
personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
personList.add(new Person("Anni", 8200, 24, "female", "New York"));
personList.add(new Person("Owen", 9500, 25, "male", "New York"));
personList.add(new Person("Alisa", 7900, 26, "female", "New York"));
personList.add(new Person("koukay", 9500, 26, "male", "New York"));
personList.add(new Person("houkay", 7800, 28, "male", "New York")); /*maxLength();
more6Print(list, 6);
findFirst(list);
more6(list);
less6(list);
more7();
findPerson(personList);
maxValue();
maxSalary(personList);
more6Count(list);
upperCaseAdd3();
addSalary(personList);
splitList();
calculate();
sumAndMax(personList);
collectTo(list,personList);
operate(personList);
group(personList);
join(personList);
collectReducing(personList);
sort(personList);
*/
distinctAndSkip();
     listMapOrder();
}
   /**
* mapList排序
*/
private static void listMapOrder(){
List<Map<String,Double>> comments= new ArrayList<>();
for (int i = 0; i <10; i++) {
Map<String,Double> map= new HashMap<>();
map.put("DateStr",Math.random());
comments.add(map);
} List<Map<String, Double>> collect = comments.stream().sorted(Comparator.comparing(StreamTest::comparingByData)).collect(Collectors.toList());
for (Map<String, Double> stringObjectMap : collect) {
System.out.println(stringObjectMap.get("DateStr"));
}
}
private static Double comparingByData(Map<String,Double> map){
return map.get("DateStr");
}

/**
* 流合并、去重、限制、跳过等操作。
*/
private static void distinctAndSkip(){
String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "d", "e", "f", "g" };
Stream<String> stream1 = Arrays.stream(arr1);
Stream<String> stream2 = Arrays.stream(arr2); // concat:合并两个流 distinct:去重
List<String> collect1 = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList()); // limit:限制从流中获得前n个数据
List<Integer> collect2 = Stream.iterate(1, x -> x + 2).limit(5).collect(Collectors.toList());
// skip:跳过前n个数据
List<Integer> collect3 = Stream.iterate(1, x -> x + 2).skip(2).limit(5).collect(Collectors.toList());
System.out.println("合并去重的结果为: "+collect1);
System.out.println("取出前五个数据: "+collect2);
System.out.println("跳过前两个数据: "+collect3);
} /**
* sorted,中间操作。有两种排序:
*
* sorted():自然排序,流中元素需实现Comparable接口
* sorted(Comparator com):Comparator排序器自定义排序
*/
private static void sort(List<Person> personList){
// 按工资增序排序
List<String> collect1 = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList());
// 按工资倒序排序
List<String> collect2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).map(Person::getName).collect(Collectors.toList());
// 先按工资再按年龄自然排序(从小到大)
List<String> collect3 = personList.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName).collect(Collectors.toList());
// 先按工资再按年龄自定义排序(从大到小)
List<String> collect4 = personList.stream().sorted((p1, p2) -> {
if (p1.getSalary() == p2.getSalary()) {
return p2.getAge() - p1.getAge();
} else {
return p2.getSalary() - p1.getSalary();
}
}).map(Person::getName).collect(Collectors.toList());
//先按工资再按年龄倒序
List<String> collect5 = personList.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName).collect(Collectors.toList());
// 先按工资再按年龄自定义排序(从大到小)
System.out.println("按工资增序排序: "+collect1);
System.out.println("按工资倒序排序: "+collect2);
System.out.println("先按工资再按年龄自然排序(从小到大): "+collect3);
System.out.println("先按工资再按年龄自定义排序(从大到小): "+collect4);
System.out.println("先按工资再按年龄倒序: "+collect5); } /**
* Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持。
*/
private static void collectReducing(List<Person> personList){
// 每个员工减去起征点后的薪资之和
Optional<Integer> reduce = personList.stream().map(p -> p.getSalary() - 5000).reduce(Integer::sum);
Integer collect = personList.stream().collect(Collectors.reducing(0, Person::getSalary, (x, y) -> (x + y - 5000)));
System.out.println("员工扣税薪资总和1:" + reduce.get());
System.out.println("员工扣税薪资总和2:" + collect); } /**
* joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。
*/
private static void join(List<Person> personList){
String collect = personList.stream().map(Person::getName).collect(Collectors.joining("--"));
System.out.println("所有成员姓名为: "+collect);
List<String> list = Arrays.asList("A", "B", "C");
String collect1 = list.stream().collect(Collectors.joining("*"));
System.out.println("拼接后的字符串为: "+collect1);
} /**
* 将员工按薪资是否高于8000分为两部分;将员工按性别和地区分组
*/
private static void group(List<Person> personList){
// 将员工按薪资是否高于8000分组
Map<Boolean, List<Person>> collect = personList.stream().collect(Collectors.partitioningBy(p -> p.getSalary() > 8000));
Map<Boolean, List<Person>> collect3 = personList.stream().collect(Collectors.groupingBy(p -> p.getSalary() > 8000));
// 将员工按性别分组
Map<String, List<Person>> collect1 = personList.stream().collect(Collectors.groupingBy(Person::getSex));
// 将员工先按性别分组,再按地区分组
Map<String, Map<String, List<Person>>> collect2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
System.out.println("员工按薪资是否大于8000分组情况:" + collect);
System.out.println("员工按薪资是否大于8000分组情况:" + collect3);
System.out.println("员工按性别分组情况:" + collect1);
System.out.println("员工按性别、地区:" + collect2);
} /**
* 统计员工人数、平均工资、工资总额、最高工资。
*/
private static void operate(List<Person> personList){
//员工人数
Long collect = personList.stream().collect(Collectors.counting());
//平均工资
Double collect1 = personList.stream().collect(Collectors.averagingDouble(p -> p.getSalary()));
//工资总额
Double collect2 = personList.stream().collect(Collectors.summingDouble(Person::getSalary));
//最高工资
Optional<Integer> collect3 = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
DoubleSummaryStatistics collect4 = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
log.info("员工人数为: {}, 平均工资为: {}, 工资总额为: {}, 最高工资为: {}, 查询工资所有为: {}",collect,collect1,collect2,collect3,collect4); }
private static void collectTo(List<Integer> list, List<Person> personList){
List<Integer> collect1 = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
Set<Integer> collect2 = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());
Map<String, Person> collect = personList.stream().filter(p -> p.getSalary() > 8000).collect(Collectors.toMap(Person::getName, p -> p));
System.out.println(collect1);
System.out.println(collect2);
System.out.println(collect);
} /**
* 求所有员工的工资之和和最高工资。
*/
private static void sumAndMax(List<Person> personList){
//员工工资之和方式一
Optional<Integer> reduce = personList.stream().map(Person::getSalary).reduce((p1, p2) -> p1 + p2);
//员工工资之和方式二
Integer reduce1 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), (sum1, sum2) -> sum1 + sum2);
//员工工资之和方式三
Optional<Integer> reduce2 = personList.stream().map(Person::getSalary).reduce(Integer::sum);
//员工工资之和方式四
Integer reduce3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum); //员工工资最高值一
Optional<Integer> reducemax1 = personList.stream().map(Person::getSalary).reduce(Integer::max);
//员工工资最高值二
Optional<Integer> reducemax2 = personList.stream().map(Person::getSalary).reduce((s1,s2)->s1>s2?s1:s2);
//员工工资最高值三
Integer reduce4 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(), Integer::max);
Integer reduce5 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary() ,(max1,max2)->max1>max2?max1:max2);
log.info("员工工资之和1为: {},员工工资之和2为: {},员工工资之和3为: {},员工工资之和4为: {}",reduce.get(),reduce1,reduce2.get(),reduce3);
log.info("员工工资最高值1: {},员工工资最高值2: {},员工工资最高值3: {},员工工资最高值4: {}",reducemax1.get(),reducemax2.get(),reduce4,reduce5);
} /**
* 求Integer集合的元素之和、乘积和最大值。
*/
private static void calculate(){
List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4);
// 求和方式1
Optional<Integer> reduce = list.stream().reduce((x, y) -> x + y);
// 求和方式2
Optional<Integer> reduce1 = list.stream().reduce(Integer::sum);
// 求和方式3
Integer reduce2 = list.stream().reduce(0, Integer::sum);
log.info("求和方式1: {}, 方式2: {}, 方式3: {}",reduce.get(),reduce1.get(),reduce2);
// 求乘积
Optional<Integer> reduce3 = list.stream().reduce((x, y) -> x * y);
log.info("求乘积为: {}",reduce3.get());
// 求最大值方式1
Optional<Integer> reduce4 = list.stream().reduce((x, y) -> x > y ? x : y);
// 求最大值方式1
Optional<Integer> reduce5 = list.stream().reduce(Integer::max);
log.info("求最大值方法1: {},方式2: {}",reduce4.get(),reduce5.get());
} /**
* 将两个字符数组合并成一个新的字符数组。
*/
private static void splitList(){
List<String> list = Arrays.asList("m,k,l,a", "1,3,5,7");
List<String> collect = list.stream().flatMap(str -> {
String[] split = str.split(",");
return Arrays.stream(split);
}).collect(Collectors.toList());
System.out.println(list);
System.out.println(collect);
} /**
* 将员工的薪资全部增加1000。
* @param personList
*/
private static void addSalary(List<Person> personList){
List<Person> collect = personList.stream().map((person) -> {
person.setSalary(person.getSalary() + 1000);
return person;
}).collect(Collectors.toList());
collect.forEach(person -> {
log.info("{}调薪后的工资为{}",person.getName(),person.getSalary());
});
} /**
* 英文字符串数组的元素全部改为大写。整数数组每个元素+3。
*/
private static void upperCaseAdd3(){
String[] strArr = { "abcd", "bcdd", "defde", "fTr" };
List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);
List<String> collect1 = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());
List<Integer> collect = intList.stream().map(x -> x + 3).collect(Collectors.toList()); collect1.forEach(a->{
log.info("每个元素大写-> "+a);
});
collect.forEach(a->{
log.info("每个元素+3-> "+a);
}); }
private static void more6Count(List<Integer> list){
long count = list.stream().filter(x -> x > 6).count();
log.info("大于6的元素有{}个",count);
}
private static void maxSalary( List<Person> personList ){
Optional<Person> max = personList.stream().max(Comparator.comparing(Person::getSalary));
System.out.println("姓名: "+max.get().getName()+"--------工资 "+max.get().getSalary());
}
private static void maxValue(){
List<Integer> list = Arrays.asList(7, 6, 9, 4, 11, 6); //自然排序
Optional<Integer> max = list.stream().max(Integer::compareTo);
//自定义排序
Optional<Integer> max1 = list.stream().max(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
});
System.out.println("自然排序的最大值:" + max.get());
System.out.println("自定义排序的最大值:" + max1.get()); }
/**
* 获取String集合中最长的元素
*/
private static void maxLength(){
List<String> list = Arrays.asList("adnm", "admmt", "potjhgfdsatfd", "xbangd", "weoujgsd");
Optional<String> max = list.stream().max(Comparator.comparing(String::length));
System.out.println(max.get()); }
/**
* 遍历输出符合条件的元素 大于6
* @param list
* @param i
*/
private static void more6Print(List<Integer> list, int i) {
list.stream().filter(x -> x > i).forEach(System.out::println);
} /**
* 匹配第一个
* @param list
*/
private static void findFirst(List<Integer> list) {
Optional<Integer> first = list.stream().filter(x -> x > 6).findFirst();
System.out.println("匹配第一个大于6的数-> "+first.get());
} /**
* // 匹配任意(适用于并行流)大于6
* @param list
*/
private static void more6(List<Integer> list) {
Optional<Integer> any = list.parallelStream().filter(x -> x > 6).findAny();
System.out.println("匹配任意(适用于并行流)大于6-> "+any.get());
} /**
* // 是否包含符合特定条件的元素 小于6
* @param list
*/
private static void less6(List<Integer> list) {
boolean b = list.stream().anyMatch(x -> x < 6);
System.out.println("是否包含小于6的元素-> "+b);
}
/**
* //筛选出Integer集合中大于7的元素,并打印出来
*/
private static void more7() {
List<Integer> list2 = Arrays.asList(6, 7, 3, 8, 1, 2, 9);
more6Print(list2, 7);
} /**
* 筛选员工中工资高于8000的人,并形成新的集合
*/
public static void findPerson(List<Person> personList){ personList.stream().filter(p -> p.getSalary() > 8000).collect(Collectors.toList()).forEach((t)->{
System.out.println("姓名: "+t.getName()+"--------工资 "+t.getSalary());
});
}
}

java8 Stream新特性的更多相关文章

  1. Java8 Stream新特性详解及实战

    Java8 Stream新特性详解及实战 背景介绍 在阅读Spring Boot源代码时,发现Java 8的新特性已经被广泛使用,如果再不学习Java8的新特性并灵活应用,你可能真的要out了.为此, ...

  2. 简单了解JAVA8的新特性

    JAVA8新特性会颠覆整个JAVA程序员的编程习惯 甚至如果您坚守JAVA7之前的编程习惯,今后你看比较年轻的程序员写的JAVA代码都会无法理解 所以为了保证不脱钩,我觉得有必要学习JAVA8的新特性 ...

  3. java8的新特性以及用法简介

    1. 介绍 2 接口的默认方法 2 lambda表达式 2.1 函数式接口 2.2 方法与构造函数引用 2.3 访问局部变量 2.4 访问对象字段与静态变量 3. 内建函数式接口 3.1 Predic ...

  4. Java8常用新特性实践

    前言: 时下Oracle开速迭代的Java社区以即将推出Java10,但尴尬的是不少小中企业仍使用JDK7甚至JDK6开发. 从上面列出的JDK8特性中我们可以发现Java8的部分特性很明显的是从Sc ...

  5. 深度分析:java8的新特性lambda和stream流,看完你学会了吗?

    1. lambda表达式 1.1 什么是lambda 以java为例,可以对一个java变量赋一个值,比如int a = 1,而对于一个方法,一块代码也是赋予给一个变量的,对于这块代码,或者说被赋给变 ...

  6. Java8的新特性以及与C#的比较

    函数式接口 VS 委托 在C中,可以使用函数指针来存储函数的入口,从而使得函数可以像变量一样赋值.传递和存储,使得函数的调用变得十分灵活,是实现函数回调的基础.然而函数指针不存在函数的签名信息,甚至可 ...

  7. java5、java6、java7、java8的新特性

    Java5: 1.泛型 Generics:        引用泛型之后,允许指定集合里元素的类型,免去了强制类型转换,并且能在编译时刻进行类型检查的好处. Parameterized Type作为参数 ...

  8. Java8部分新特性的学习

    Java8中的新特性 一.Lambda表达式 Lambda表达式可以理解为一种可传递的匿名函数:它没有名称,但又参数列表.函数主体.返回类型,可能还有一个可以抛出的异常列表. 匿名:和匿名类类似的,它 ...

  9. java7与java8的新特性

    java7 新特性: 1. switch 里面的 case 条件可以使用字符串了. 2. 运用 List\tempList = new ArrayList<>(); 即泛型实例化类型自动判 ...

随机推荐

  1. numpy教程05---ndarray的高级操作

    欢迎关注公众号[Python开发实战], 获取更多内容! 工具-numpy numpy是使用Python进行数据科学的基础库.numpy以一个强大的N维数组对象为中心,它还包含有用的线性代数,傅里叶变 ...

  2. 微信小程序实战,用vue3实现每日浪漫情话推荐~

    之前做了个恋爱话术微信小程序,实现高情商的恋爱聊天. 但最近突然发现,每天早上给女朋友发一段优美情话可以让她开心一整天,但无奈自己的语言水平确实有限,不能随手拈来,着实让人有点不爽. 不过办法总比困难 ...

  3. 在定义C++, C通用接口函数时让C++接口支持默认参数

    在SOUI4的开发中,所有SOUI核心对象都采用了一种类似COM接口的技术来导出接口. 这所以采用这种方案,主要目的是为了让SOUI4支持C语言调用,扩展SOUI的使用场景. 众所周知,C++函数的参 ...

  4. 集合——Collection接口,List接口

    集合:对象的容器,定义了对多个对象进行操作的常用方法.可实现数组的功能 集合和数组的区别: 数组长度固定,集合长度不固定 数组可以存储基本数据类型和引用数据类型,集合只能存储引用数据类型. 集合的位置 ...

  5. PyTorch 广播机制

    PyTorch 广播机制 定义 PyTorch的tensor参数可以自动扩展其大小.一般的是小一点的会变大,来满足运算需求. 规则 满足一下情况的tensor是可以广播的. 至少有一个维度 两个ten ...

  6. MySQL进阶之常用函数

    我的小站 有时候,除了简单的数据查询,我们还有一些高级的函数. MySQL 包含了大量并且丰富的函数,这套 MySQL 函数大全只收集了几十个常用的,剩下的比较罕见的函数我们就不再整理了,读者可以到M ...

  7. sentinel基础概念及使用

    点赞再看,养成习惯,微信搜索「小大白日志」关注这个搬砖人. 文章不定期同步公众号,还有各种一线大厂面试原题.我的学习系列笔记. 什么是sentinel sentinel是Spring Cloud Al ...

  8. SpringBoot 如何统一后端返回格式

    在前后端分离的项目中后端返回的格式一定要友好,不然会对前端的开发人员带来很多的工作量.那么SpringBoot如何做到统一的后端返回格式呢?今天我们一起来看看. 为什么要对SpringBoot返回统一 ...

  9. python学习-Day33

    目录 今日内容详细 socket socket套接字简介 socket模块 服务端 客户端 通信循环 服务端 客户端 链接循环 半连接池 概念 产生半连接的两种情况 黏包问题 多次发送被并为一次 TC ...

  10. .NET混合开发解决方案6 检测是否已安装合适的WebView2运行时

    系列目录     [已更新最新开发文章,点击查看详细] 长青版WebView2运行时将作为Windows 11操作系统的一部分包含在内.但是在Windows 11之前(Win10.Win8.1.Win ...