Java8 之Stream用法总结

一、创建Stream

从集合创建Stream

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> stream = numbers.stream();

从数组创建Stream

int[] array = {1, 2, 3, 4, 5};
IntStream stream = Arrays.stream(array);

使用Stream.of()创建Stream

Stream stream = Stream.of(“a”, “b”, “c”);

二、中间操作

filter():过滤满足条件的元素。

案例1

List<Integer> evenNumbers = numbers.stream()
                                    .filter(n -> n % 2 == 0)
                                    .collect(Collectors.toList());

案例2

   //原方法
   public static void main(String[] args) {
 
        List<String> lines = Arrays.asList("spring", "hibernate", "neo4j");
        List<String> result = getFilterOutput(lines, "neo4j");
        for (String temp : result) {
            System.out.println(temp);  
        }
 
    }
 
    private static List<String> getFilterOutput(List<String> lines, String filter) {
        List<String> result = new ArrayList<>();
        for (String line : lines) {
            if (!filter.equals(line)) {
                result.add(line);
            }
        }
        return result;
    }
 

    //stream优化
    public static void main(String[] args) {
        List<String> lines = Arrays.asList("spring", "hibernate", "neo4j");
        List<String> result = lines.stream()                // 转化为一个流
                .filter(line -> !"neo4j".equals(line))     // 排除 'String'
                .collect(Collectors.toList());              // 吧输出流收集回List中
        result.forEach(System.out::println);                //输出 : spring, hibernate
    }

案例3

package com.god.genius.baisc.jdk.jdk8.streamFilter.student;
 
 
import java.time.LocalDate;
import java.util.List;
 
public class StudentInfo implements Comparable<StudentInfo> {
 
    //名称
    private String name;
 
    //性别 true男 false女
    private Boolean gender;
 
    //年龄
    private Integer age;
 
    //身高
    private Double height;
 
    //出生日期
    private LocalDate birthday;
 
    public StudentInfo(String name, Boolean gender, Integer age, Double height, LocalDate birthday){
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.height = height;
        this.birthday = birthday;
    }
 
    @Override
    public String toString(){
        String info = String.format("%s\t\t%s\t\t%s\t\t\t%s\t\t%s",this.name,this.gender.toString(),this.age.toString(),this.height.toString(),birthday.toString());
        return info;
    }
 
    public static void printStudents(List<StudentInfo> studentInfos){
        System.out.println("[姓名]\t\t[性别]\t\t[年龄]\t\t[身高]\t\t[生日]");
        System.out.println("----------------------------------------------------------");
        studentInfos.forEach(s->System.out.println(s.toString()));
        System.out.println(" ");
    }
 
    @Override
    public int compareTo(StudentInfo ob) {
        return this.age.compareTo(ob.getAge());
        //return 1;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Boolean getGender() {
        return gender;
    }
 
    public void setGender(Boolean gender) {
        this.gender = gender;
    }
 
    public Integer getAge() {
        return age;
    }
 
    public void setAge(Integer age) {
        this.age = age;
    }
 
    public Double getHeight() {
        return height;
    }
 
    public void setHeight(Double height) {
        this.height = height;
    }
 
    public LocalDate getBirthday() {
        return birthday;
    }
 
    public void setBirthday(LocalDate birthday) {
        this.birthday = birthday;
    }
}

测试代码

package com.god.genius.baisc.jdk.jdk8.streamFilter.student;
 
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * @author lisir
 */
public class Demo {
    public static void main(String[] args) {
        List<StudentInfo> list = new ArrayList<>();
        list.add(new StudentInfo("李白", true, 18, 1.76, LocalDate.of(2001, 3, 23)));
        list.add(new StudentInfo("大乔", false, 18, 1.68, LocalDate.of(2001, 6, 3)));
        list.add(new StudentInfo("凯皇", true, 19, 1.82, LocalDate.of(2000, 3, 11)));
        list.add(new StudentInfo("小乔", false, 17, 1.61, LocalDate.of(2002, 10, 18)));
 
        //查询所有英雄
        StudentInfo.printStudents(list);
        //查找18岁的英雄
        List<StudentInfo> collect = list.stream().filter(s -> s.getAge() == 19).collect(Collectors.toList());
        StudentInfo.printStudents(collect);
 
        综合查询:查找身高在1.8米及以上且年龄小于19岁的英雄
        List<StudentInfo> boys = list.stream().filter(s -> s.getGender() && s.getHeight() >= 1.66 && s.getAge() < 19).collect(Collectors.toList());
        //输出查找结果
        StudentInfo.printStudents(boys);
 
        list.forEach(s -> System.out.println(s.toString()));
        list.stream().forEach(s->System.out.println(s.toString()));
 
    }
}

案例4: Streams 中 filter(), findAny() 和 orElse()的用法

 public static void main(String[] args) {
 
        List<User> userList = Arrays.asList(
                new User("mkyong", 30),
                new User("jack", 20),
                new User("lawrence", 40)
        );
 
        User result = getStudentByName(userList, "jack");
        System.out.println(result);
 
    }
 
 private static User getStudentByName(List<User> userList, String name) {
        User result = null;
        for (User temp : userList) {
            if (name.equals(temp.getName())) {
                result = temp;
            }
        }
        return result;
 }

public static void main(String[] args) {
 
        List<User> userList = Arrays.asList(
                new User("张三", 30),
                new User("李四", 20),
                new User("Enoch", 40)
        );
        User result1 = userList.stream()                        // 转化为流
                .filter(x -> "Enoch".equals(x.getName()))       // 只过滤出"Enoch"
                .findAny()                                      // 如果找到了就返回
                .orElse(null);                                  // 如果找不到就返回null
 
        System.out.println(result1);
 
        User result2 = userList.stream()
                .filter(x -> "Enoch".equals(x.getName()))
                .findAny()
                .orElse(null);
 
        System.out.println(result2);
 
    }

public static void main(String[] args) {
 
        List<User> userList = Arrays.asList(
                new User("张三", 30),
                new User("李四", 20),
                new User("Enoch", 40)
        );
        User result1 = userList.stream()
                .filter((p) -> "李四".equals(p.getName()) && 20 == p.getAge())
                .findAny()
                .orElse(null);
        System.out.println("result 1 :" + result1);
 
        //或者这样写
        User result2 = userList.stream()
                .filter(p -> "Enoch".equals(p.getName()) && 20 == p.getAge()).findAny()
                .orElse(null);
        System.out.println("result 2 :" + result2);
}

map():对每个元素执行某种操作并返回一个新的Stream。

List<String> upperCaseNames = names.stream()
                                   .map(String::toUpperCase)
                                   .collect(Collectors.toList());

 public static void main(String[] args) {
        List<User> userList = Arrays.asList(
                new User("张三", 30),
                new User("李四", 20),
                new User("Enoch", 40)
        );
        String name = userList.stream()
                .filter(x -> "Enoch".equals(x.getName()))
                .map(User::getName)                        //把流转化为String,这里其实就是
                                          //把一个新的事物转为另外一种事物了,类型得到了转换
                .findAny()
                .orElse("");
        System.out.println("name : " + name);
        List<String> collect = userList.stream()
                .map(User::getName)
                .collect(Collectors.toList());
        collect.forEach(System.out::println);
    }

flatMap():将多个Stream组合成一个Stream。

List<Integer> flattenedList = listOfLists.stream()
                                          .flatMap(List::stream)
                                          .collect(Collectors.toList());

distinct():去除重复元素。

List<Integer> distinctNumbers = numbers.stream()
                                       .distinct()
                                       .collect(Collectors.toList());

sorted():对元素进行排序。

List<Integer> sortedNumbers = numbers.stream()
                                     .sorted()
                                     .collect(Collectors.toList());

limit():截取Stream的前n个元素。

List<Integer> limitedNumbers = numbers.stream()
                                      .limit(3)
                                      .collect(Collectors.toList());

skip():跳过Stream的前n个元素。

List<Integer> skippedNumbers = numbers.stream()
                                      .skip(3)
                                      .collect(Collectors.toList

三、终端操作

forEach():遍历Stream中的每个元素。

numbers.stream()
       .forEach(System.out::println);

filterLists.stream().forEach(s -> System.out.println(s));

Stream.generate(random).limit(10).forEach(System.out::println);//可传入方法

roster.stream().parallel().filter(p1.negate()).forEach(p -> t.test§);//也可以实现接口

strList.forEach(System.out::println)

        // 创建出一个数组
        List<String> strList = Arrays.asList("YangHang", "AnXiaoHei", "LiuPengFei");
 
        strList.forEach(System.out::println);

首先, 我们看一下是java.lang.Iterable下的一个默认方法forEach调用的,一看到这个function包下面的被@FunctionalInterface注解声明的Consumer接口, 瞬间就了然了, 这不又是函数式编程搞的鬼么?
现在的问题应该很明朗了, System.out::println这段代码其实就是Consumer接口的一个实现方式啊。

具体是怎么实现,如下代码。

    @Test
    public void testDemo2() {
        List<String> strList = Arrays.asList("YangHang", "AnXiaoHei", "LiuPengFei");
 
        strList.forEach(x -> {
            System.out.println(x);
        });
    }

然后, 我们惊喜的发现和上面的代码运行结果是一制的, 我们基本上可以断定, 上面那种写法是下面这种的一种缩写形式。 就是把你遍历出来的每一个对象都用来去调用System.out(也就是PrintStream类的一个实例)的println方法。
最后, 大家是不是有一个想法, 想自己写一个Consumer接口的实现类, 让foreach调用一下。

public class PrintUtil {
 
    /**
     * 对要遍历的元素添加add操作
     */
    public void addString(String x) {
        System.out.println(x + "add");
    }
}

然后, 我们这么来玩

    @Test
    public void testDemo3() {
        List<String> strList = Arrays.asList("YangHang", "AnXiaoHei", "LiuPengFei");
 
        strList.forEach(new PrintUtil()::addString);
    }

运行一下, 果然可以的。
但是发现, 如果是静态方法的时候必须得用类名双冒号静态方法, 这估计是语法的一种, 注意就好。

count():统计Stream中元素的数量。

long count = numbers.stream()
                    .count();

collect():将Stream中的元素收集到一个集合中。

List<Integer> collectedNumbers = numbers.stream()
                                        .collect(Collectors.toList());

min():查找Stream中的最小元素。

Optional<Integer> minNumber = numbers.stream()
                                     .min(Integer::compareTo);
if (minNumber.isPresent()) {
    System.out.println("Min number: " + minNumber.get());
}

max():查找Stream中的最大元素。

Optional<Integer> maxNumber = numbers.stream()
                                     .max(Integer::compareTo);
if (maxNumber.isPresent()) {
    System.out.println("Max number: " + maxNumber.get());
}

reduce():对Stream中的元素进行计算。

Optional<Integer> sum = numbers.stream()
                               .reduce(Integer::sum);
if (sum.isPresent()) {
    System.out.println("Sum: " + sum.get());
}

anyMatch():判断Stream中是否存在满足条件的元素。

boolean hasEvenNumber = numbers.stream()
                              .anyMatch(n -> n % 2 == 0);

allMatch():判断Stream中的所有元素是否都满足条件。

boolean allPositive = numbers.stream()
                            .allMatch(n -> n > 0);

noneMatch():判断Stream中的所有元素是否都不满足条件。

boolean noneNegative = numbers.stream()
                              .noneMatch(n -> n < 0);

四、样例演示

1、处理Person对象列表,及一些常见的数据操作

假设我们有一个Person类,它具有姓名、年龄和性别属性。我们要处理一个包含多个Person对象的列表,并进行一些常见的数据操作。以下是使用Java 8的Stream常用用法处理这个复杂数据的示例代码:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 
public class Main {
    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("John", 25, Gender.MALE),
                new Person("Jane", 30, Gender.FEMALE),
                new Person("Tom", 20, Gender.MALE),
                new Person("Susan", 28, Gender.FEMALE),
                new Person("Mike", 35, Gender.MALE)
        );
 
        // 使用Stream的常用用法
 
        // 1. 按年龄升序排列,并获取姓名列表
        List<String> sortedNames = persons.stream()
                .sorted((p1, p2) -> p1.getAge() - p2.getAge())
                .map(Person::getName)
                .collect(Collectors.toList());
        System.out.println(sortedNames);
 
        // 2. 获取所有年龄大于25岁的人的姓名列表
        List<String> namesAbove25 = persons.stream()
                .filter(p -> p.getAge() > 25)
                .map(Person::getName)
                .collect(Collectors.toList());
        System.out.println(namesAbove25);
 
        // 3. 统计男性和女性的人数
        long maleCount = persons.stream()
                .filter(p -> p.getGender() == Gender.MALE)
                .count();
        long femaleCount = persons.stream()
                .filter(p -> p.getGender() == Gender.FEMALE)
                .count();
        System.out.println("Male count: " + maleCount);
        System.out.println("Female count: " + femaleCount);
 
        // 4. 按性别分组
        Map<Gender, List<Person>> personsByGender = persons.stream()
                .collect(Collectors.groupingBy(Person::getGender));
        System.out.println(personsByGender);
 
        // 5. 计算年龄的平均值
        double averageAge = persons.stream()
                .mapToInt(Person::getAge)
                .average()
                .orElse(0);
        System.out.println("Average age: " + averageAge);
    }
}
 
class Person {
    private String name;
    private int age;
    private Gender gender;
 
    public Person(String name, int age, Gender gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
 
    public String getName() {
        return name;
    }
 
    public int getAge() {
        return age;
    }
 
    public Gender getGender() {
        return gender;
    }
 
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender=" + gender +
                '}';
    }
}
 
enum Gender {
    MALE, FEMALE
}

这段代码使用了Stream的排序、映射、过滤、计数、分组和统计等常用操作,展示了如何在处理复杂数据时利用Stream提供的功能。根据实际需要,可以组合使用这些操作来完成更复杂的数据处理任务。

2、学生老师和课程,及一些常见的数据操作

假设我们有一个包含学生、老师和课程的复杂数据结构。学生和老师都有姓名和年龄属性,课程有名称和标签属性。我们要处理这个复杂数据结构,并进行一些常见的数据操作。以下是使用Java 8的Stream常用用法处理这个复杂数据的示例代码:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 
public class Main {
    public static void main(String[] args) {
        // 创建学生
        Student student1 = new Student("John", 20);
        Student student2 = new Student("Jane", 22);
        Student student3 = new Student("Tom", 23);
        List<Student> students = Arrays.asList(student1, student2, student3);
 
        // 创建老师
        Teacher teacher1 = new Teacher("Amy", 35);
        Teacher teacher2 = new Teacher("Bob", 40);
        List<Teacher> teachers = Arrays.asList(teacher1, teacher2);
 
        // 创建课程
        Course course1 = new Course("Math", "science");
        Course course2 = new Course("English", "language");
        Course course3 = new Course("Physics", "science");
        List<Course> courses = Arrays.asList(course1, course2, course3);
 
        // 学生选课
        student1.selectCourse(course1);
        student1.selectCourse(course2);
        student2.selectCourse(course2);
        student2.selectCourse(course3);
        student3.selectCourse(course1);
        student3.selectCourse(course3);
 
        // 按照年龄升序排列学生
        List<Student> sortedStudents = students.stream()
                .sorted((s1, s2) -> s1.getAge() - s2.getAge())
                .collect(Collectors.toList());
        System.out.println(sortedStudents);
 
        // 获取学生姓名列表
        List<String> studentNames = students.stream()
                .map(Student::getName)
                .collect(Collectors.toList());
        System.out.println(studentNames);
 
        // 获取学生所选的课程名列表
        List<String> studentCourseNames = students.stream()
                .flatMap(student -> student.getCourses().stream())
                .map(Course::getName)
                .collect(Collectors.toList());
        System.out.println(studentCourseNames);
 
        // 获取选择了"science"标签的课程
        List<Course> scienceCourses = courses.stream()
                .filter(course -> course.getLabel().equals("science"))
                .collect(Collectors.toList());
        System.out.println(scienceCourses);
 
        // 根据老师的年龄分组学生
        Map<Teacher, List<Student>> studentsByTeacher = students.stream()
                .collect(Collectors.groupingBy(Student::getTeacher));
        System.out.println(studentsByTeacher);
    }
}
 
class Student {
    private String name;
    private int age;
    private List<Course> courses;
    private Teacher teacher;
 
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
        this.courses = new ArrayList<>();
    }
 
    public String getName() {
        return name;
    }
 
    public int getAge() {
        return age;
    }
 
    public List<Course> getCourses() {
        return courses;
    }
 
    public Teacher getTeacher() {
        return teacher;
    }
 
    public void selectCourse(Course course) {
        courses.add(course);
        course.addStudent(this);
    }
 
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
 
class Teacher {
    private String name;
    private int age;
 
    public Teacher(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public int getAge() {
        return age;
    }
 
    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
 
class Course {
    private String name;
    private String label;
    private List<Student> students;
 
    public Course(String name, String label) {
        this.name = name;
        this.label = label;
        this.students = new ArrayList<>();
    }
 
    public String getName() {
        return name;
    }
 
    public String getLabel() {
        return label;
    }
 
    public List<Student> getStudents() {
        return students;
    }
 
    public void addStudent(Student student) {
        students.add(student);
        student.teacher = student.getTeacher();
    }
 
    @Override
    public String toString() {
        return "Course{" +
                "name='" + name + '\'' +
                ", label='" + label + '\'' +
                '}';
    }
}

这段代码演示了如何使用Stream对包含学生、老师和课程的复杂数据进行处理。它展示了在使用Stream时常见的一些操作,如排序、映射、过滤、分组等。根据实际需求,你可以在此基础上进一步扩展和优化数据操作。

3、公司部门用户和商品订单,及一些常见的数据操作

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
class User {
    private String name;
    private String company;
    private String department;
 
    public User(String name, String company, String department) {
        this.name = name;
        this.company = company;
        this.department = department;
    }
 
    public String getName() {
        return name;
    }
 
    public String getCompany() {
        return company;
    }
 
    public String getDepartment() {
        return department;
    }
}
 
class Order {
    private String product;
    private int quantity;
 
    public Order(String product, int quantity) {
        this.product = product;
        this.quantity = quantity;
    }
 
    public String getProduct() {
        return product;
    }
 
    public int getQuantity() {
        return quantity;
    }
}
 
public class StreamExample {
    public static void main(String[] args) {
        List<User> users = Arrays.asList(
                new User("John", "Company A", "Department A"),
                new User("Tom", "Company B", "Department B"),
                new User("Alice", "Company A", "Department B")
        );
 
        List<Order> orders = Arrays.asList(
                new Order("Product A", 5),
                new Order("Product B", 3),
                new Order("Product A", 2)
        );
 
        // 1. 根据公司分组用户
        Map<String, List<User>> usersByCompany = users.stream()
                .collect(Collectors.groupingBy(User::getCompany));
        System.out.println("Users grouped by company: " + usersByCompany);
 
        // 2. 过滤用户,只保留来自公司 A 的用户
        List<User> usersFromCompanyA = users.stream()
                .filter(u -> u.getCompany().equals("Company A"))
                .collect(Collectors.toList());
        System.out.println("Users from Company A: " + usersFromCompanyA);
 
        // 3. 获取部门为 Department B 的用户数量
        long departmentBUserCount = users.stream()
                .filter(u -> u.getDepartment().equals("Department B"))
                .count();
        System.out.println("Department B user count: " + departmentBUserCount);
 
        // 4. 获取每个用户的订单总数
        Map<User, Integer> orderCountByUser = users.stream()
                .collect(Collectors.toMap(
                        u -> u,
                        u -> orders.stream()
                                .filter(o -> o.getProduct().equals("Product A"))
                                .mapToInt(Order::getQuantity)
                                .sum()
                ));
        System.out.println("Order count by user: " + orderCountByUser);
 
        // 5. 获取所有订单的总数量
        int totalOrderCount = orders.stream()
                .mapToInt(Order::getQuantity)
                .sum();
        System.out.println("Total order count: " + totalOrderCount);
    }
}

这个示例代码展示了使用 JDK 8 Stream API 进行一些常见的数据处理操作,包括分组、过滤、计数和求和等操作。你可以根据实际的复杂数据结构和需求来进行相应的修改和扩展。

4、公司部门用户和商品订单,n个示例

过滤过程:
假设有一个用户列表List users,过滤出年龄大于18岁的用户:

List<User> filteredUsers = users.stream()
        .filter(user -> user.getAge() > 18)
        .collect(Collectors.toList());

映射过程:
假设有一个用户列表List users,提取所有用户的用户名:

List<String> usernames = users.stream()
        .map(user -> user.getUsername())
        .collect(Collectors.toList());

排序过程:
假设有一个用户列表List users,按照年龄从小到大排序:

List<User> sortedUsers = users.stream()
        .sorted(Comparator.comparingInt(User::getAge))
        .collect(Collectors.toList());

分组过程:
假设有一个订单列表List orders,根据公司进行分组:

Map<Company, List<Order>> ordersByCompany = orders.stream()
        .collect(Collectors.groupingBy(Order::getCompany));

聚合操作:
假设有一个订单列表List orders,计算所有订单的总金额:

double totalAmount = orders.stream()
        .mapToDouble(Order::getAmount)
        .sum();

扁平化处理:
假设有一个公司列表List companies,获取所有公司的部门列表:

List<Department> departments = companies.stream()
        .flatMap(company -> company.getDepartments().stream())
        .collect(Collectors.toList());

匹配元素:
假设有一个用户列表List users,检查是否存在年龄大于等于30岁的用户:

boolean anyMatch = users.stream()
        .anyMatch(user -> user.getAge() >= 30);

查找元素:
假设有一个用户列表List users,查找年龄最大的用户:

Optional<User> maxAgeUser = users.stream()
        .max(Comparator.comparingInt(User::getAge));

限制结果集:
假设有一个订单列表List orders,获取前5个订单:

List<Order> limitedOrders = orders.stream()
        .limit(5)
        .collect(Collectors.toList());

跳过元素:
假设有一个商品列表List products,跳过前3个商品,获取剩下的商品:

List<Product> skippedProducts = products.stream()
        .skip(3)
        .collect(Collectors.toList());

去重处理:
假设有一个整数列表List numbers,去除重复的数字:

List<Integer> distinctNumbers = numbers.stream()
        .distinct()
        .collect(Collectors.toList());

并行处理:
假设有一个订单列表List orders,使用并行流计算订单的总金额:

double totalAmount = orders.parallelStream()
        .mapToDouble(Order::getAmount)
        .sum();

使用reduce聚合操作:
假设有一个订单列表List orders,计算所有订单的总金额,使用reduce操作:

double totalAmount = orders.stream()
        .map(Order::getAmount)
        .reduce(0.0, Double::sum);

使用findFirst查找第一个元素:
假设有一个订单列表List orders,查找第一个购买商品为“手机”的订单:

Optional<Order> firstMobileOrder = orders.stream()
        .filter(order -> order.getProduct().equals("手机"))
        .findFirst();

对集合元素进行批量操作:
假设有一个用户列表List users,将所有用户的年龄加5并更新:

List<User> updatedUsers = users.stream()
        .peek(user -> user.setAge(user.getAge() + 5))
        .collect(Collectors.toList());

多级分组:
假设有一个商品列表List products,按照公司和部门进行多级分组:

Map<Company, Map<Department, List<Product>>> productsByCompanyAndDepartment = products.stream()
        .collect(Collectors.groupingBy(Product::getCompany,
                Collectors.groupingBy(Product::getDepartment)));

使用flatMap进行嵌套处理:
假设有一个公司列表List companies,获取所有公司的所有部门的所有员工姓名:

List<String> employeeNames = companies.stream()
        .flatMap(company -> company.getDepartments().stream())
        .flatMap(department -> department.getEmployees().stream())
        .map(Employee::getName)
        .collect(Collectors.toList());

查找满足条件的任意元素:
假设有一个商品列表List products,查找任意一件库存大于0的商品:

Optional<Product> anyProduct = products.stream()
        .filter(product -> product.getStock() > 0)
        .findAny();

统计元素个数:
假设有一个用户列表List users,统计用户的数量:

long userCount = users.stream()
        .count();

使用forEach进行迭代操作:
假设有一个订单列表List orders,打印所有订单的信息:

orders.stream()
        .forEach(System.out::println);

并行处理处理大数据量:
假设有一个非常大的用户列表List users,使用并行流进行处理:

users.parallelStream()
        .filter(user -> user.getAge() > 18)
        .forEach(System.out::println);

使用collect进行自定义的聚合操作:
假设有一个商品列表List products,将所有商品的名称用逗号连接起来:

String names = products.stream()
        .map(Product::getName)
        .collect(Collectors.joining(", "));

使用Optional处理可能为空的值:
假设有一个List<Optional> userList,筛选出非空的用户列表:

List<User> nonEmptyUserList = userList.stream()
        .filter(Optional::isPresent)
        .map(Optional::get)
        .collect(Collectors.toList());

连接字符串:
假设有一个商品列表List products,将所有商品的名称以逗号分隔连接成一个字符串:

String joinedNames = products.stream()
        .map(Product::getName)
        .collect(Collectors.joining(", "));

对元素进行分页处理:
假设有一个订单列表List orders,将订单按照每页10个进行分页:

int pageSize = 10;
int totalPages = (int) Math.ceil((double) orders.size() / pageSize);
 
List<List<Order>> paginatedOrders = IntStream.range(0, totalPages)
        .mapToObj(page -> orders.stream()
                .skip(page * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList()))
        .collect(Collectors.toList());

使用IntStream进行数值操作:
假设有一个整数列表List numbers,计算列表中所有偶数的平方和:

int sumOfEvenSquares = numbers.stream()
        .filter(number -> number % 2 == 0)
        .mapToInt(number -> number * number)
        .sum();

使用max和min获取最大值和最小值:
假设有一个整数列表List numbers,找到列表中的最大值和最小值:

Optional<Integer> maxNumber = numbers.stream()
        .max(Integer::compareTo);
 
Optional<Integer> minNumber = numbers.stream()
        .min(Integer::compareTo);

使用toMap将集合转换为Map:
假设有一个用户列表List users,将用户按照ID作为键转换为Map:

Map<Integer, User> userMap = users.stream()
        .collect(Collectors.toMap(User::getId, Function.identity()));

使用anyMatch和allMatch进行条件判断:
假设有一个用户列表List users,检查是否所有用户的年龄都大于18岁:

boolean allAdults = users.stream()
        .allMatch(user -> user.getAge() > 18);
 
boolean anyAdult = users.stream()
        .anyMatch(user -> user.getAge() > 18);

使用distinct和sorted进行去重和排序:
假设有一个整数列表List numbers,去除重复值并对值进行排序:

List<Integer> distinctSortedNumbers = numbers.stream()
        .distinct()
        .sorted()
        .collect(Collectors.toList());

使用flatMap将多个列表合并为一个列表:
假设有一个公司列表List companies,将每个公司的部门列表合并成一个部门列表:

List<Department> allDepartments = companies.stream()
        .flatMap(company -> company.getDepartments().stream())
        .collect(Collectors.toList());

使用reduce进行自定义聚合操作:
假设有一个订单列表List orders,计算所有订单的总金额:

double totalAmount = orders.stream()
        .map(Order::getAmount)
        .reduce(0.0, Double::sum);

使用partitioningBy进行分区操作:
假设有一个商品列表List products,按照库存是否大于0进行分区:

Map<Boolean, List<Product>> partitionedProducts = products.stream()
        .collect(Collectors.partitioningBy(product -> product.getStock() > 0));

使用zip操作将两个流合并为一个流:
假设有一个用户列表List users和一个商品列表List products,将两个列表合并为一个交替的流:

Stream interleavedStream = StreamUtils.zip(users.stream(), products.stream());

使用iterate生成一个无限流:
假设需要生成一个自增的整数序列:

Stream sequentialNumberStream = Stream.iterate(0, i -> i + 1);

使用toList将流转换为列表:
假设有一个用户流Stream userStream,将其转换为用户列表:

List userList = userStream.collect(Collectors.toList());

使用toSet将流转换为集合:
假设有一个商品流Stream productStream,将其转换为商品集合:

Set productSet = productStream.collect(Collectors.toSet());

使用joining将流转换为字符串:
假设有一个部门流Stream departmentStream,将其转换为部门名称的逗号分隔字符串:

String departmentNames = departmentStream.map(Department::getName)
                    .collect(Collectors.joining(", "));

使用summarizingInt计算流中的统计数据:
假设有一个订单流Stream orderStream,计算订单金额的统计数据:

DoubleSummaryStatistics orderStatistics = orderStream
        .collect(Collectors.summarizingDouble(Order::getAmount));
System.out.println("Total Orders: " + orderStatistics.getCount());
System.out.println("Total Amount: " + orderStatistics.getSum());
System.out.println("Average Amount: " + orderStatistics.getAverage());
System.out.println("Max Amount: " + orderStatistics.getMax());
System.out.println("Min Amount: " + orderStatistics.getMin());

使用toMap将流转换为自定义的Map:
假设有一个用户流Stream userStream,将其转换为以ID为键、用户对象为值的Map:

Map<Integer, User> userMap = userStream.collect(Collectors.toMap(User::getId, Function.identity()));

使用groupingByConcurrent进行并发分组操作:
假设有一个订单列表List orders,按照公司进行并发分组:

ConcurrentMap<Company, List<Order>> ordersByCompany = orders.stream()
        .collect(Collectors.groupingByConcurrent(Order::getCompany));

使用flatMapToInt计算流中元素的数值总和:
假设有一个整数列表List numbers,计算列表中所有元素的数值总和:

int sum = numbers.stream()
        .flatMapToInt(IntStream::of)
        .sum();

使用peek进行调试操作:
假设有一个商品列表List products,在对每个商品进行其他操作之前,在控制台打印商品信息:

List<Product> modifiedProducts = products.stream()
        .peek(product -> System.out.println("Processing product: " + product.getName()))
        .map(product -> /* 进行其他操作 */)
        .collect(Collectors.toList());
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值