Java8 Stream常见用法

Stream流的常见用法:

1.利用stream流特性把数组转list集合

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//打印结果
System.out.println(list);

输出结果为:

2.利用stream流特性取出list集合中的最大值

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性获取集合中的最大值
Integer max = list.stream().max(Comparator.comparing(Integer::new)).get();
//打印结果
System.out.println(max);

输出结果为:

3.利用stream流特性取出list集合中的最小值

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性获取集合中的最
Integer min= list.stream().min(Comparator.comparing(Integer::new)).get();
//打印结果
System.out.println(min);

输出结果为:

4.利用stream流特性取出list集合中大于3的值

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性获取集合中大于3的所有值
List<Integer> conditions =

list.stream().filter(value -> value > 3).collect(Collectors.toList());
//打印结果
System.out.println(conditions);

输出结果:

5.利用stream流特性取出list集合中小于3的值

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性获取集合中小于3的所有值
List<Integer> conditions = list.stream().filter(value -> value < 3).collect(Collectors.toList());
//打印结果
System.out.println(conditions);

输出结果:

6.利用stream流特性取出list集合中不等于3的值

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性获取集合中不等于3的值
List<Integer> conditions = list.stream().filter(value -> value != 3).collect(Collectors.toList());
//打印结果
System.out.println(conditions);

输出结果:

7.利用stream流特性计算list集合中大于1的数量

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性获取集合中大于1数量
long count = list.stream().filter(value -> value > 1).count();
//打印结果
System.out.println(count);

输出结果:

8.利用stream流特性计算list集合中等于2的数量

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性获取集合中等于2的数量
long count = list.stream().filter(value -> value == 2).count();
//打印结果
System.out.println(count);

输出结果:

9.利用stream流特性去除list集合中重复的数据

//定义一个数组
Integer[] array = {5,5,2,2,1,1,6,6,4,4,3,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性去除集合中重复的数据
List<Integer> collects = list.stream().distinct().collect(Collectors.toList());
//打印结果
System.out.println("去除前的数据:" + list + "\n去重后的数据:" + collects);

输出结果:

10.利用stream流特性截取list集合中前两个的数据

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性截取集合中前两个数值
List<Integer> collects = list.stream().limit(2).collect(Collectors.toList());
//打印结果
System.out.println("截取到的数据:" + collects);

输出结果:

11.利用stream流特性跳过list集合中前两个数据

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性跳过集合中前两个数值
List<Integer> collects = list.stream().skip(2).collect(Collectors.toList());
//打印结果
System.out.println("跳过前两个值后的数据:" + collects);

输出结果:

12.利用stream流特性遍历list集合中每一个元素

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性遍历集合中每一个元素
list.stream().forEach(System.out::println);

输出结果:

13.利用stream流特性计算list集合中数值的平均值

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性计算集合中数值的平均值
double average = list.stream().mapToInt(Integer::new).average().orElse(0);
//打印结果
System.out.println("计算后的平均值:" + average);

输出结果:

14.利用stream流特性计算list集合中数值的总和

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性计算集合中数值的总和
int sum = list.stream().mapToInt(Integer::new).sum();
//打印结果
System.out.println("计算后的总和:" + sum);

输出结果:

15.利用stream流特性升序排列list集合中所有元素

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性升序排列集合中的所有元素
List<Integer> collects = list.stream().sorted().collect(Collectors.toList());
//打印结果
System.out.println("升序排列后的集合:" + collects);

输出结果:

16.利用stream流特性降序排列list集合中所有元素

//定义一个数组
Integer[] array = {5,2,1,6,4,3};
//通过stream特性把数组转list集合
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//通过stream特性降序排列集合中的所有元素
List<Integer> collects = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
//打印结果
System.out.println("降序排列后的集合:" + collects);

输出结果:

结合实际拓展使用:

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

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

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Stream {


    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.*;
import java.util.stream.Collectors;
public class Stream {
    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 {
    public Teacher teacher;
    private String name;
    private int age;
    private List<Course> courses;

    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.*;
import java.util.stream.Collectors;
public class Stream {
    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);
    }

}

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;
    }
}

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

  4、公司部门用户和商品订单,n个示例
    过滤过程:
    假设有一个用户列表List<User> users,过滤出年龄大于18岁的用户:

    List<User> filteredUsers = users.stream()
            .filter(user -> user.getAge() > 18)
            .collect(Collectors.toList());
    映射过程:
    假设有一个用户列表List<User> users,提取所有用户的用户名:

    List<String> usernames = users.stream()
            .map(user -> user.getUsername())
            .collect(Collectors.toList());
    排序过程:
    假设有一个用户列表List<User> users,按照年龄从小到大排序:

    List<User> sortedUsers = users.stream()
            .sorted(Comparator.comparingInt(User::getAge))
            .collect(Collectors.toList());
    分组过程:
    假设有一个订单列表List<Order> orders,根据公司进行分组:

    Map<Company, List<Order>> ordersByCompany = orders.stream()
            .collect(Collectors.groupingBy(Order::getCompany));
    聚合操作:
    假设有一个订单列表List<Order> orders,计算所有订单的总金额:

    double totalAmount = orders.stream()
            .mapToDouble(Order::getAmount)
            .sum();
    扁平化处理:
    假设有一个公司列表List<Company> companies,获取所有公司的部门列表:

    List<Department> departments = companies.stream()
            .flatMap(company -> company.getDepartments().stream())
            .collect(Collectors.toList());
    匹配元素:
    假设有一个用户列表List<User> users,检查是否存在年龄大于等于30岁的用户:

    boolean anyMatch = users.stream()
            .anyMatch(user -> user.getAge() >= 30);
    查找元素:
    假设有一个用户列表List<User> users,查找年龄最大的用户:

    Optional<User> maxAgeUser = users.stream()
            .max(Comparator.comparingInt(User::getAge));
    限制结果集:
    假设有一个订单列表List<Order> orders,获取前5个订单:

    List<Order> limitedOrders = orders.stream()
            .limit(5)
            .collect(Collectors.toList());
    跳过元素:
    假设有一个商品列表List<Product> products,跳过前3个商品,获取剩下的商品:

    List<Product> skippedProducts = products.stream()
            .skip(3)
            .collect(Collectors.toList());
    去重处理:
    假设有一个整数列表List<Integer> numbers,去除重复的数字:

    List<Integer> distinctNumbers = numbers.stream()
            .distinct()
            .collect(Collectors.toList());
    并行处理:
    假设有一个订单列表List<Order> orders,使用并行流计算订单的总金额:

    double totalAmount = orders.parallelStream()
            .mapToDouble(Order::getAmount)
            .sum();
    使用reduce聚合操作:
    假设有一个订单列表List<Order> orders,计算所有订单的总金额,使用reduce操作:

    double totalAmount = orders.stream()
            .map(Order::getAmount)
            .reduce(0.0, Double::sum);
    使用findFirst查找第一个元素:
    假设有一个订单列表List<Order> orders,查找第一个购买商品为手机的订单:

    Optional<Order> firstMobileOrder = orders.stream()
            .filter(order -> order.getProduct().equals("手机"))
            .findFirst();
    对集合元素进行批量操作:
    假设有一个用户列表List<User> users,将所有用户的年龄加5并更新:

    List<User> updatedUsers = users.stream()
            .peek(user -> user.setAge(user.getAge() + 5))
            .collect(Collectors.toList());
    多级分组:
    假设有一个商品列表List<Product> products,按照公司和部门进行多级分组:

    Map<Company, Map<Department, List<Product>>> productsByCompanyAndDepartment = products.stream()
            .collect(Collectors.groupingBy(Product::getCompany,
                    Collectors.groupingBy(Product::getDepartment)));
    使用flatMap进行嵌套处理:
    假设有一个公司列表List<Company> companies,获取所有公司的所有部门的所有员工姓名:

    List<String> employeeNames = companies.stream()
            .flatMap(company -> company.getDepartments().stream())
            .flatMap(department -> department.getEmployees().stream())
            .map(Employee::getName)
            .collect(Collectors.toList());
    查找满足条件的任意元素:
    假设有一个商品列表List<Product> products,查找任意一件库存大于0的商品:

    Optional<Product> anyProduct = products.stream()
            .filter(product -> product.getStock() > 0)
            .findAny();
    统计元素个数:
    假设有一个用户列表List<User> users,统计用户的数量:

    long userCount = users.stream()
            .count();
    使用forEach进行迭代操作:
    假设有一个订单列表List<Order> orders,打印所有订单的信息:

            orders.stream()
            .

    forEach(System.out::println);

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

            users.parallelStream()
            .

    filter(user ->user.getAge()>18)
            .

    forEach(System.out::println);

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

    String names = products.stream()
            .map(Product::getName)
            .collect(Collectors.joining(", "));
    使用Optional处理可能为空的值:
    假设有一个List<Optional<User>> userList,筛选出非空的用户列表:

    List<User> nonEmptyUserList = userList.stream()
            .filter(Optional::isPresent)
            .map(Optional::get)
            .collect(Collectors.toList());
    连接字符串:
    假设有一个商品列表List<Product> products,将所有商品的名称以逗号分隔连接成一个字符串:

    String joinedNames = products.stream()
            .map(Product::getName)
            .collect(Collectors.joining(", "));
    对元素进行分页处理:
    假设有一个订单列表List<Order> 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<Integer> numbers,计算列表中所有偶数的平方和:

    int sumOfEvenSquares = numbers.stream()
            .filter(number -> number % 2 == 0)
            .mapToInt(number -> number * number)
            .sum();
    使用maxmin获取最大值和最小值:
    假设有一个整数列表List<Integer> numbers,找到列表中的最大值和最小值:

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

    Optional<Integer> minNumber = numbers.stream()
            .min(Integer::compareTo);
    使用toMap将集合转换为Map
    假设有一个用户列表List<User> users,将用户按照ID作为键转换为Map

    Map<Integer, User> userMap = users.stream()
            .collect(Collectors.toMap(User::getId, Function.identity()));
    使用anyMatchallMatch进行条件判断:
    假设有一个用户列表List<User> users,检查是否所有用户的年龄都大于18岁:

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

    boolean anyAdult = users.stream()
            .anyMatch(user -> user.getAge() > 18);
    使用distinctsorted进行去重和排序:
    假设有一个整数列表List<Integer> numbers,去除重复值并对值进行排序:

    List<Integer> distinctSortedNumbers = numbers.stream()
            .distinct()
            .sorted()
            .collect(Collectors.toList());
    使用flatMap将多个列表合并为一个列表:
    假设有一个公司列表List<Company> companies,将每个公司的部门列表合并成一个部门列表:

    List<Department> allDepartments = companies.stream()
            .flatMap(company -> company.getDepartments().stream())
            .collect(Collectors.toList());
    使用reduce进行自定义聚合操作:
    假设有一个订单列表List<Order> orders,计算所有订单的总金额:

    double totalAmount = orders.stream()
            .map(Order::getAmount)
            .reduce(0.0, Double::sum);
    使用partitioningBy进行分区操作:
    假设有一个商品列表List<Product> products,按照库存是否大于0进行分区:

    Map<Boolean, List<Product>> partitionedProducts = products.stream()
            .collect(Collectors.partitioningBy(product -> product.getStock() > 0));
    使用zip操作将两个流合并为一个流:
    假设有一个用户列表List<User> users和一个商品列表List<Product>products,将两个列表合并为一个交替的流:

    Stream<Object> interleavedStream = StreamUtils.zip(users.stream(), products.stream());
    使用iterate生成一个无限流:
    假设需要生成一个自增的整数序列:

    Stream<Integer> sequentialNumberStream = Stream.iterate(0, i -> i + 1);
    使用toList将流转换为列表:
    假设有一个用户流Stream<User> userStream,将其转换为用户列表:

    List<User> userList = userStream.collect(Collectors.toList());
    使用toSet将流转换为集合:
    假设有一个商品流Stream<Product> productStream,将其转换为商品集合:

    Set<Product> productSet = productStream.collect(Collectors.toSet());
    使用joining将流转换为字符串:
    假设有一个部门流Stream<Department> departmentStream,将其转换为部门名称的逗号分隔字符串:

    String departmentNames = departmentStream.map(Department::getName)
            .collect(Collectors.joining(", "));
    使用summarizingInt计算流中的统计数据:
    假设有一个订单流Stream<Order> 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<User> userStream,将其转换为以ID为键、用户对象为值的Map

    Map<Integer, User> userMap = userStream.collect(Collectors.toMap(User::getId, Function.identity()));
    使用groupingByConcurrent进行并发分组操作:
    假设有一个订单列表List<Order> orders,按照公司进行并发分组:

    ConcurrentMap<Company, List<Order>> ordersByCompany = orders.stream()
            .collect(Collectors.groupingByConcurrent(Order::getCompany));
    使用flatMapToInt计算流中元素的数值总和:
    假设有一个整数列表List<Integer> numbers,计算列表中所有元素的数值总和:

    int sum = numbers.stream()
            .flatMapToInt(IntStream::of)
            .sum();
    使用peek进行调试操作:
    假设有一个商品列表List<Product> products,在对每个商品进行其他操作之前,在控制台打印商品信息:

    List<Product> modifiedProducts = products.stream()
            .peek(product -> System.out.println("Processing product: " + product.getName()))
            .map(product -> /* 进行其他操作 */)
            .collect(Collectors.toList());
    五、
    常用总结
            根据mapkey进行排序
    升序排列
    Map<LocalDateTime, List<ExerciseReport>> twelveReportMap = twelveReportDataList.stream()
            .collect(Collectors.groupingBy(ExerciseReport::getCreateDate));
        System.out.println("twelveReportMap"+twelveReportMap);
    //根据时间进行升序排序
    Map<LocalDateTime, List<ExerciseReport>> result = new LinkedHashMap<>();
        twelveReportMap.entrySet().

    stream().

    sorted(Map.Entry.comparingByKey()).

    forEachOrdered(x ->result.put(x.getKey(),x.getValue()));
    降序排列
    Map<LocalDateTime, List<ExerciseReport>> twelveReportMap = twelveReportDataList.stream()
            .collect(Collectors.groupingBy(ExerciseReport::getCreateDate));
    //根据时间进行升序排序
    Map<LocalDateTime, List<ExerciseReport>> result = new LinkedHashMap<>();
        twelveReportMap.entrySet().

    stream().

    sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).

    forEachOrdered(x ->result.put(x.getKey(),x.getValue()));
    String[] idStr转化为
    List<Long> ids
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

    public class Main {
        public static void main(String[] args) {
            String[] idStr = {"1", "2", "3", "4", "5"};

            List<Long> ids = Arrays.stream(idStr)
                    .map(Long::parseLong)
                    .collect(Collectors.toList());

            System.out.println(ids);
        }
    }

       感谢大家的阅读,觉得有用的朋友可以收藏点赞,有问题的朋友可以留下你的问题一起交流讨论。

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

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

相关文章

【数学建模】DVD在线租赁

2005高教社杯全国大学生数学建模竞赛题目B 随着信息时代的到来&#xff0c;网络成为人们生活中越来越不可或缺的元素之一。许多网站利用其强大的资源和知名度&#xff0c;面向其会员群提供日益专业化和便捷化的服务。例如&#xff0c;音像制品的在线租赁就是一种可行的服务。这…

Vue 使用Canvas画布手写电子版签名 保存 上传服务端

电子版签名效果 定义画布 <canvas width"500"height"250"ref"cn"mousedown"cnMouseDown"mousemove"cnMouseMove"mouseup"cnMouseUp"style"width:500px;height: 250px;background-color:snow;padding: 10p…

算法学习003-银行存钱 中小学算法思维学习 信奥算法解析 c++实现

目录 C银行存钱 一、题目要求 1、编程实现 2、输入输出 二、算法分析 三、程序编写 四、程序说明 五、运行结果 六、考点分析 七、推荐资料 C银行存钱 一、题目要求 1、编程实现 小明的父亲准备为小明的4年大学生活一次性在银行储蓄一笔钱&#xff0c;使用整存零取…

某赛通电子文档安全管理系统 多处 SQL注入漏洞复现

0x01 产品简介 某赛通电子文档安全管理系统(简称:CDG)是一款电子文档安全加密软件,该系统利用驱动层透明加密技术,通过对电子文档的加密保护,防止内部员工泄密和外部人员非法窃取企业核心重要数据资产,对电子文档进行全生命周期防护,系统具有透明加密、主动加密、智能…

文章解读与仿真程序复现思路——电网技术EI\CSCD\北大核心《适用于含新能源交流电网继电保护整定计算的故障计算方法研究》

本专栏栏目提供文章与程序复现思路&#xff0c;具体已有的论文与论文源程序可翻阅本博主免费的专栏栏目《论文与完整程序》 论文与完整源程序_电网论文源程序的博客-CSDN博客https://blog.csdn.net/liang674027206/category_12531414.html 电网论文源程序-CSDN博客电网论文源…

数据结构:初识集合框架

目录 1. 什么是集合框架2. 集合框架的重要性3. 背后所涉及的数据结构以及算法3.1 什么是数据结构3.2 容器背后对应的数据结构3.3 相关java知识3.4 什么是算法 1. 什么是集合框架 官方教程 Java 集合框架Java Collection Framework &#xff0c;又被称为容器和其实现类classes …

神经网络的激活函数

目录 神经网络 激活函数 sigmoid 激活函数 tanh 激活函数 backward方法 relu 激活函数 softmax 激活函数 神经网络 人工神经网络&#xff08; Artificial Neural Network&#xff0c; 简写为ANN&#xff09;也简称为神经网络&#xff08;NN&#xff09;&#xff0c…

LeetCode - LCR 008.长度最小的子数组

一. 题目链接 LeetCode - 209. 长度最小的子数组 二. 思路分析 由于此问题分析的对象是「⼀段连续的区间」&#xff0c;因此可以考虑「滑动窗口」的思想来解决这道题。 让滑动窗口满足&#xff1a;从 i 位置开始&#xff0c;窗口内所有元素的和小于target &#xff08;那么当…

Linux基础——Linux开发工具(gcc/g++,gdb)

前言&#xff1a;在上一篇我们简单介绍了yum&#xff0c;vim的一些常用的指令和模式&#xff0c;现在让我们来进一步了解其他的Linux环境基础开发工具gcc/g&#xff0c;gdb。 如果对前面yum和vim有什么不懂的建议回顾去回顾上期知识&#xff01;&#xff01;&#xff01; Linu…

【问题实操】银河麒麟高级服务器操作系统实例,CPU软锁报错触发宕机

1.服务器环境以及配置 处理器&#xff1a; Kunpeng 920 内存&#xff1a; 256G DDR4 整机类型/架构&#xff1a; TaiShan 200 (Model 2280) 内核版本 4.19.90-23.8.v2101.ky10.aarch64 2.问题现象描述 两台搭载麒麟v10 sp1的机器均在系统CPU软锁报错时&#xff0c;触…

sCrypt全新上线RUNES功能

sCrypt智能合约平台全新上线一键etch/mint RUNES功能&#xff01; 请访问 https://runes.scrypt.io/ 或点击阅读原文体验&#xff01; 关于sCrypt sCrypt是BSV区块链上的一种智能合约高级语言。比特币使用基于堆栈的Script语言来支持智能合约&#xff0c;但是用原生Script编…

JavaScript创建和填充数组的更多方法

空数组fill()方法创建并填充数组 ● 我们之前创建数组的方式都是手动去创建去一个数据&#xff0c;例如 console.log([1, 2, 3, 4, 5, 6, 7]);● 当然我们也可以使用Array对象来构造数组 console.log([1, 2, 3, 4, 5, 6, 7]); console.log(new Array(1, 2, 3, 4, 5, 6, 7));…