前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Java】Java流中的API

【Java】Java流中的API

作者头像
人不走空
发布2024-06-11 08:27:35
810
发布2024-06-11 08:27:35
举报
文章被收录于专栏:学习与分享学习与分享

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

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

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

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

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

代码语言:javascript
复制
<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. 统计学

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

代码语言:javascript
复制
<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>

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

代码语言:javascript
复制
<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>

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

代码语言:javascript
复制
<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

代码语言:javascript
复制
<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 将嵌套结构展平到单个流中。

代码语言:javascript
复制
<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>

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

代码语言:javascript
复制
<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>

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

代码语言:javascript
复制
<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 还可用于执行各种统计操作,例如计数、平均等。

代码语言:javascript
复制
<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>

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

代码语言:javascript
复制
<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 元素。

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

统计学:执行统计操作。

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-06-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概述: Java Stream API 有助于处理元素序列,提供过滤、映射和减少等操作。流可用于以声明方式执行操作,类似于对数据的类似 SQL 的操作
  • 关键概念: 流:支持顺序和并行聚合操作的元素序列
  • 使用案例 :
  • 摘要: Java Stream API 是用于处理集合和数据的强大工具。它允许:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档