【Java】Java流中的API

简介: 【Java】Java流中的API

概述:

Java Stream API 有助于处理元素序列,提供过滤、映射和减少等操作。流可用于以声明方式执行操作,类似于对数据的类似 SQL 的操作

关键概念:

流:支持顺序和并行聚合操作的元素序列

中间操作:返回另一个流且延迟的操作(例如,filter、map)

码头运营:产生结果或副作用且不懒惰的操作(例如,collect、forEach)

示例场景:

假设我们有一个 Person 对象列表,并且我们希望使用 Stream API 对该列表执行各种操作

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>public class Person {
    private String name;
    private int age;
    private String city;
 
    public Person(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }
 
    public String getName() {
        return name;
    }
 
    public int getAge() {
        return age;
    }
 
    public String getCity() {
        return city;
    }
 
    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + ", city='" + city + "'}";
    }
}
</code></span></span>

使用案例 :

  1. 滤波
  2. 映射
  3. 收集
  4. 减少
  5. 平面映射
  6. 排序
  7. 查找和匹配
  8. 统计学

滤波:过滤允许您选择与给定条件匹配的元素

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 
public class Main {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30, "New York"),
            new Person("Bob", 20, "Los Angeles"),
            new Person("Charlie", 25, "New York"),
            new Person("David", 40, "Chicago")
        );
 
        // Filter people older than 25
        List<Person> filteredPeople = people.stream().filter(person -> person.getAge() > 25)                                       .collect(Collectors.toList());
        filteredPeople.forEach(System.out::println);
    }
}
</code></span></span>

映射:映射使用函数将每个元素转换为另一种形式

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>public class Main {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30, "New York"),
            new Person("Bob", 20, "Los Angeles"),
            new Person("Charlie", 25, "New York"),
            new Person("David", 40, "Chicago")
        );
        // Get list of names
        List<String> names = people.stream()
                                   .map(Person::getName)
                                   .collect(Collectors.toList());
        names.forEach(System.out::println);
    }
}
</code></span></span>

收集:收集将流的元素收集到集合或其他数据结构中

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>public class Main {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30, "New York"),
            new Person("Bob", 20, "Los Angeles"),
            new Person("Charlie", 25, "New York"),
            new Person("David", 40, "Chicago")
        );
        // Collect names into a set
        Set<String> uniqueCities = people.stream()
         .map(Person::getCity).collect(Collectors.toSet());
        uniqueCities.forEach(System.out::println);
    }
}
</code></span></span>

减少:Reducing 使用关联累积函数对流的元素执行 Reduction 并返回 Optional

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>public class Main {
    public static void main(String[] args) {
         List<Person> people = Arrays.asList(
            new Person("Alice", 30, "New York"),
            new Person("Bob", 20, "Los Angeles"),
            new Person("Charlie", 25, "New York"),
            new Person("David", 40, "Chicago")
        );
        // Sum of ages
        int totalAge = people.stream()
                 .map(Person::getAge).reduce(0, Integer::sum);
        System.out.println("Total Age: " + totalAge);
    }
}
</code></span></span>

平面映射 :FlatMapping 将嵌套结构展平到单个流中。

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>public class Main {
    public static void main(String[] args) {
        List<List<String>> namesNested = Arrays.asList(
            Arrays.asList("John", "Doe"),
            Arrays.asList("Jane", "Smith"),
            Arrays.asList("Peter", "Parker")
        );
 
        List<String> namesFlat = namesNested.stream()
             .flatMap(List::stream).collect(Collectors.toList());
        namesFlat.forEach(System.out::println);
    }
}
</code></span></span>

排序:排序允许您对流的元素进行排序

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>public class Main {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30, "New York"),
            new Person("Bob", 20, "Los Angeles"),
            new Person("Charlie", 25, "New York"),
            new Person("David", 40, "Chicago")
        );
 
        // Sort by age
        List<Person> sortedPeople = people.stream()
            .sorted(Comparator.comparing(Person::getAge))
            .collect(Collectors.toList());
        sortedPeople.forEach(System.out::println);
    }
}
</code></span></span>

查找和匹配:

查找和匹配操作检查流的元素,看看它们是否与给定的谓词匹配

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>public class Main {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30, "New York"),
            new Person("Bob", 20, "Los Angeles"),
            new Person("Charlie", 25, "New York"),
            new Person("David", 40, "Chicago")
        );
 
        // Find any person living in New York
        Optional<Person> personInNY = people.stream()
               .filter(person -> "NewYork".equals(person.getCity())).findAny();
 
        personInNY.ifPresent(System.out::println);
 
        // Check if all people are older than 18
        boolean allAdults = people.stream()
          .allMatch(person -> person.getAge() > 18);
 
        System.out.println("All adults: " + allAdults);
    }
}
 
</code></span></span>

统计学:Stream API 还可用于执行各种统计操作,例如计数、平均等。

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>public class Main {
    public static void main(String[] args) {
       List<Person> people = Arrays.asList(
            new Person("Alice", 30, "New York"),
            new Person("Bob", 20, "Los Angeles"),
            new Person("Charlie", 25, "New York"),
            new Person("David", 40, "Chicago")
        );
 
        // Count number of people
        long count = people.stream().count();
        System.out.println("Number of people: " + count);
 
        // Calculate average age
        Double averageAge = people.stream()
        .collect(Collectors.averagingInt(Person::getAge));
 
        System.out.println("Average Age: " + averageAge);
    }
}
 
</code></span></span>

实际示例:

这是一个使用上述几个功能的综合示例:

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>import java.util.*;
import java.util.stream.*;
 
public class Main {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person("Alice", 30, "New York"),
            new Person("Bob", 20, "Los Angeles"),
            new Person("Charlie", 25, "New York"),
            new Person("David", 40, "Chicago")
        );
 
        // Filter, map, sort, and collect
        List<String> names = people.stream()
                                   .filter(person -> person.getAge() > 20)
                                   .map(Person::getName)
                                   .sorted()
                                   .collect(Collectors.toList());
 
        names.forEach(System.out::println);
 
        // Find the oldest person
        Optional<Person> oldestPerson = people.stream()
                                              .max(Comparator.comparing(Person::getAge));
 
        oldestPerson.ifPresent(person -> System.out.println("Oldest Person: " + person));
 
        // Group by city
        Map<String, List<Person>> peopleByCity = people.stream()
                                                       .collect(Collectors.groupingBy(Person::getCity));
 
        peopleByCity.forEach((city, peopleInCity) -> {
            System.out.println("People in " + city + ": " + peopleInCity);
        });
 
        // Calculate total and average age
        IntSummaryStatistics ageStatistics = people.stream()
                                                   .collect(Collectors.summarizingInt(Person::getAge));
 
        System.out.println("Total Age: " + ageStatistics.getSum());
        System.out.println("Average Age: " + ageStatistics.getAverage());
    }
}
 
</code></span></span>

摘要:

Java Stream API 是用于处理集合和数据的强大工具。它允许:

滤波:根据条件选择元素

映射:转换元素

收集:将元素收集到集合或其他数据结构中

减少:将元素组合成一个结果。

平面映射:展平嵌套结构。

排序:Order 元素。

查找和匹配:根据条件检查元素。

统计学:执行统计操作。

了解这些功能将帮助您编写更简洁、更简洁、更易读的代码。

相关文章
|
12天前
|
Java API
深入探讨 Java 8 集合操作:全面解析 Stream API 的强大功能
深入探讨 Java 8 集合操作:全面解析 Stream API 的强大功能
18 2
|
2天前
|
监控 安全 Java
java中并发Queue种类与各自API特点
java中并发Queue种类与各自API特点
16 0
|
4天前
|
Java API 索引
java中String类常用API
java中String类常用API
|
5天前
|
Java API
java调用个人微信API接口收发朋友圈,删除评论朋友圈
java调用个人微信API接口收发朋友圈,删除评论朋友圈
|
7天前
|
Java 大数据 API
Java中的Lambda表达式和Stream API的高效使用
【6月更文挑战第18天】在Java 8中引入的Lambda表达式和Stream API为集合操作带来了革命性的改进,提供了一种更加简洁、声明式的编程方式。本文将深入探讨如何利用这些特性来提升代码的可读性和开发效率,同时避免常见的性能陷阱。
|
7天前
|
存储 Java 大数据
Java Stream API
Java Stream API
12 1
|
8天前
|
存储 Java API
Java常用的API(4)
Java常用的API
11 1
|
1天前
|
缓存 JSON Java
使用Java进行RESTful API开发的最佳实践
使用Java进行RESTful API开发的最佳实践
|
1天前
|
Java 机器人 程序员
Java中的lambda表达式与Stream API:高效的函数式编程
Java中的lambda表达式与Stream API:高效的函数式编程