【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 元素。

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

统计学:执行统计操作。

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

相关文章
|
25天前
|
Java API 数据处理
Java新特性:使用Stream API重构你的数据处理
Java新特性:使用Stream API重构你的数据处理
|
1月前
|
Java 大数据 API
Java Stream API:现代集合处理与函数式编程
Java Stream API:现代集合处理与函数式编程
191 100
|
1月前
|
Java API 数据处理
Java Stream API:现代集合处理新方式
Java Stream API:现代集合处理新方式
209 101
|
1月前
|
并行计算 Java 大数据
Java Stream API:现代数据处理之道
Java Stream API:现代数据处理之道
187 101
|
2月前
|
JSON Java API
【干货满满】分享京东API接口到手价,用Java语言实现
本示例使用 Java 调用京东开放平台商品价格及优惠信息 API,通过商品详情和促销接口获取到手价(含优惠券、满减等),包含签名生成、HTTP 请求及响应解析逻辑,适用于比价工具、电商系统集成等场景。
|
2月前
|
存储 Java API
Java Stream API:现代数据处理之道
Java Stream API:现代数据处理之道
335 188
|
2月前
|
存储 Java API
Java Stream API:现代数据处理之道
Java Stream API:现代数据处理之道
241 92
|
3月前
|
Oracle Java 关系型数据库
掌握Java Stream API:高效集合处理的利器
掌握Java Stream API:高效集合处理的利器
353 80
|
3月前
|
安全 Java API
Java 8 Stream API:高效集合处理的利器
Java 8 Stream API:高效集合处理的利器
240 83
|
1月前
|
安全 Java API
使用 Java 构建强大的 REST API 的四个基本技巧
本文结合探险领域案例,分享Java构建REST API的四大核心策略:统一资源命名、版本控制与自动化文档、安全防护及标准化异常处理,助力开发者打造易用、可维护、安全可靠的稳健API服务。
136 2