Java 8 stream的详细用法
话不多说,直接看代码演示
/**
* @description: stream 练习
* @author: hwx
* @date: 2022/02/10
**/
public class stream {
static 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;
} public Person(String name, int salary, String sex, String area) {
this.name = name;
this.salary = salary;
this.sex = sex;
this.area = area;
} // 省略了get和set,请自行添加 public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getSalary() {
return salary;
} public void setSalary(int salary) {
this.salary = salary;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public String getArea() {
return area;
} public void setArea(String area) {
this.area = area;
} @Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", salary=" + salary +
", age=" + age +
", sex='" + sex + '\'' +
", area='" + area + '\'' +
'}';
}
} public static void main(String[] args) {
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Tom", 8900, "male", "New York"));
personList.add(new Person("Tom", 8800, "male", "New York"));
personList.add(new Person("Jack", 7000, "male", "Washington"));
personList.add(new Person("Lily", 7800, "female", "Washington"));
personList.add(new Person("Anni", 8200, "female", "New York"));
personList.add(new Person("Owen", 9500, "male", "New York"));
personList.add(new Person("Alisa", 7900, "female", "New York")); //遍历输出符合条件的元素
personList.stream().filter(e -> e.salary > 8000).forEach(System.out::println);
//筛选薪资大于8000的
List<Person> collect = personList.stream().filter(e -> e.salary > 8000).collect(Collectors.toList());
// List<Person> collect22 = personList.stream().filter(e -> e::getSalary>8000).collect(Collectors.toList());
Set<Person> collect1 = personList.stream().filter(e -> e.salary > 8000).collect(Collectors.toSet());
//去重
Map<String, Integer> collect2 = personList.stream().filter(e -> e.salary > 8000).collect(Collectors.toMap(e -> e.name, e -> e.salary,(a1,a2)->a2));
//.map用法
List<String> collect3 = personList.stream().filter(e -> e.salary > 8000).map(e -> e.name).collect(Collectors.toList()); // 匹配第一个
Optional<Person> first = personList.stream().filter(e -> e.salary > 8000).findFirst();
// 匹配任意(适用于并行流)
Optional<Person> first1 = personList.parallelStream().filter(e -> e.salary > 8000).findFirst();
// 是否包含符合特定条件的元素
boolean b = personList.stream().anyMatch(e -> e.salary > 8000); System.out.println(collect);
System.out.println(collect1);
System.out.println(collect2);
System.out.println(collect3);
System.out.println("匹配第一个"+first);
System.out.println("匹配任意(适用于并行流)"+first1);
System.out.println("是否包含符合特定条件的元素"+b); //筛选出名字最长的
Optional<Person> max = personList.stream().max(Comparator.comparing(e -> e.name.length()));
//筛选出工资最高的
Optional<Person> max1 = personList.stream().max(Comparator.comparing(e -> e.salary));
System.out.println("筛选出名字最长的"+max);
System.out.println("筛选出工资最高的"+max1); //筛选出工资大于8000的总人数
long count = personList.stream().filter(e -> e.salary > 8000).count();
System.out.println("筛选出工资大于8000的总人数"+count); String[] strArr = { "abcd", "bcdd", "defde", "fTr" };
//英文字符串数组的元素全部改为大写
List<String> collect4 = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());
System.out.println("英文字符串数组的元素全部改为大写"+collect4); List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11);
//整数数组每个元素+3
List<Integer> collect5 = intList.stream().map(e -> e + 3).collect(Collectors.toList());
System.out.println("整数数组每个元素+3"+collect5); //将员工的薪资全部增加1000。
List<Integer> collect6 = personList.stream().map(e -> e.salary + 1000).collect(Collectors.toList());
System.out.println("将员工的薪资全部增加1000"+collect6);
List<Person> collect7 = personList.stream().map(e -> {
Person person = new Person(e.name, e.salary, e.sex, e.area);
person.setSalary(person.salary + 1000);
return person;
}).collect(Collectors.toList());
System.out.println("(不改变原先结构)将员工的薪资全部增加1000"+collect7);
/* List<Person> collect8 = personList.stream().map(e -> {
e.setSalary(e.salary + 1000);
return e;
}).collect(Collectors.toList());
System.out.println("(不改变原先结构)将员工的薪资全部增加1000(原先的list被改变)"+collect8);*/ //将两个字符数组合并成一个新的字符数组
List<String> list = Arrays.asList("m,k,l,a", "1,3,5,7");
List<String> collect9 = list.stream().flatMap(e -> {
// 将每个元素转换成一个stream
String[] split = e.split(",");
Stream<String> s2 = Arrays.stream(split);
return s2;
}).collect(Collectors.toList());
System.out.println("将两个字符数组合并成一个新的字符数组"+collect9); //求所有员工的工资之和
Optional<Integer> reduce = personList.stream().map(Person::getSalary).reduce(Integer::sum);
System.out.println("求所有员工的工资之和"+reduce);
Integer reduce1 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), (sum1, sum2) -> sum1 + sum2);
System.out.println("求所有员工的工资之和"+reduce1);
Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum);
System.out.println("求所有员工的工资之和"+sumSalary3); // 求员工总数
Long collect10 = personList.stream().collect(Collectors.counting());
System.out.println("求员工总数"+collect10);
// 求平均工资
Double collect11 = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
System.out.println("求平均工资"+collect11);
// 求最高工资
Optional<Integer> collect12 = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
System.out.println("求最高工资"+collect12);
// 求工资之和
Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
System.out.println("员工工资总和:" + sum);
// 一次性统计所有信息
DoubleSummaryStatistics collect13 = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
System.out.println("员工工资所有统计:" + collect13); //分组
// 将员工按薪资是否高于8000分组
Map<Boolean, List<Person>> collect8 = personList.stream().collect(Collectors.partitioningBy(e -> e.getSalary() > 8000));
System.out.println("将员工按薪资是否高于8000分组"+collect8);
// 将员工按性别分组
Map<String, List<Person>> collect14 = personList.stream().collect(Collectors.groupingBy(Person::getSex));
System.out.println("将员工按性别分组"+collect14);
// 将员工先按性别分组,再按地区分组
Map<String, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
System.out.println("将员工先按性别分组,再按地区分组"+group2); //接合
String names = personList.stream().map(p -> p.getName()).collect(Collectors.joining(","));
System.out.println("所有员工的姓名:" + names); //排序
// 按工资升序排序(自然排序)
List<String> newList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName)
.collect(Collectors.toList());
System.out.println("按工资升序排序(自然排序)"+newList);
// 按工资倒序排序
List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
.map(Person::getName).collect(Collectors.toList());
System.out.println("按工资倒序排序"+newList);
// 先按工资再按年龄升序排序
List<String> newList3 = personList.stream()
.sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName)
.collect(Collectors.toList());
System.out.println("先按工资再按年龄升序排序:" + newList3);
// 先按工资再按年龄自定义排序(降序)
List<String> newList4 = 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());
System.out.println("先按工资再按年龄自定义降序排序:" + newList4); String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "d", "e", "f", "g" }; Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
// concat:合并两个流 distinct:去重
List<String> newList8 = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
// limit:限制从流中获得前n个数据
List<Integer> collect88 = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
// skip:跳过前n个数据
List<Integer> collect888 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList()); System.out.println("流合并:" + newList8);
System.out.println("limit:" + collect88);
System.out.println("skip:" + collect888); }
}
Java 8 stream的详细用法的更多相关文章
- Java中stream的详细用法
来自于:Java 8 stream的详细用法_旅行者-CSDN博客_java stream 一.概述 Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行 ...
- Java中System的详细用法
System.arraycopy System.arraycopy的函数原型是: public static void arraycopy(Object src, int srcPos, Object ...
- Java中TreeSet的详细用法
第1部分 TreeSet介绍 TreeSet简介 TreeSet 是一个有序的集合,它的作用是提供有序的Set集合.它继承于AbstractSet抽象类,实现了NavigableSet, Clonea ...
- Java中Collections类详细用法
1.sort(Collection)方法的使用(含义:对集合进行排序). 例:对已知集合c进行排序? public class Practice { public static void main(S ...
- Java中继承的详细用法
关于上一篇构造方法后的继承方法 构造方法链接 extends是继承的关键字 例: 下面的代码BB和CC就是AA的子类 允许一个父类有多个子类,但不允许一个子类有多个父类 /*final*/ class ...
- 讲透JAVA Stream的collect用法与原理,远比你想象的更强大
大家好,又见面了. 在我前面的文章<吃透JAVA的Stream流操作,多年实践总结>中呢,对Stream的整体情况进行了细致全面的讲解,也大概介绍了下结果收集器Collectors的常见用 ...
- 【转】java.util.vector中的vector的详细用法
[转]java.util.vector中的vector的详细用法 ArrayList会比Vector快,他是非同步的,如果设计涉及到多线程,还是用Vector比较好一些 import java.uti ...
- Java 8 Stream 用法
一.Stream是什么 Stream 不是集合元素,它不是数据结构并不保存数据,它是有关算法和计算的,它更像一个高级版本的 Iterator.原始版本的 Iterator,用户只能显式地一个一个遍历元 ...
- java集合 stream 相关用法(1)
java8新增一种流式数据,让操作集合数据更简单方便. 定义基本对象: public class Peo { private String name; private String id; publi ...
随机推荐
- Mysql的存储过程摘要
MySQL 5.0 版本开始支持存储过程. 存储过程(Stored Procedure)是一种在数据库中存储复杂程序,以便外部程序调用的一种数据库对象. 存储过程是为了完成特定功能的SQL语句集,经编 ...
- Oracle update和select 关联
Oracle update和select 关联 目录 Oracle update和select 关联 1.介绍 2.解决方法 2.1.需求 2.2.错误演示 2.3.解决方法 1.介绍 本文主要向大家 ...
- Git使用:版本回退
在Git中,我们可以用 git log命令查看我们修改的历史记录 C:\Users\Administrator\Documents\GitHub\learngit [master]> git l ...
- java基础05-类型转换
java基础05-类型转换 由于Java是强类型语言,所以要进行有些运算的时候,需要用到类型转换. 低 ---------------------------> 高 byte , short , ...
- 《剑指offer》面试题10- II. 青蛙跳台阶问题
问题描述 一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶.求该青蛙跳上一个 n 级的台阶总共有多少种跳法. 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008, ...
- 【Android】安卓中的存储
[Android]安卓中的存储 1.存储在App内部 最简单的一种.在尝试过程中发现,手机中很多文件夹都没有权限读写.我们可以将我们需要写的文件存放到App中的files文件夹中,当然我们有权限在整个 ...
- 【刷题-LeetCode】153 Find Minimum in Rotated Sorted Array
Find Minimum in Rotated Sorted Array Suppose an array sorted in ascending order is rotated at some p ...
- entity framework无法写入数据库.SaveChanges()失败
参考https://stackoverflow.com/questions/26745184/ef-cant-savechanges-to-db/28256645 https://www.codepr ...
- 华为联运游戏审核驳回:在未安装或需更新HMS Core的手机上,提示安装,点击取消后,游戏卡屏(集成的6.1.0.301版本游戏SDK)
问题描述 更新游戏SDK到6.1.0.301版本之后,游戏包被审核驳回:在未安装或需更新华为移动服务版本(HMS Core)的手机上,提示安装华为移动服务(HMS Core),点击取消,游戏卡屏.修改 ...
- 推荐召回--基于用户的协同过滤UserCF
目录 1. 前言 2. 原理 3. 数据及相似度计算 4. 根据相似度计算结果 5. 相关问题 5.1 如何提炼用户日志数据? 5.2 用户相似度计算很耗时,有什么好的方法? 5.3 有哪些改进措施? ...