个人技术分享

 

dd3f5d43598c2a98a8352180c00a09de.png

人不走空

 

                                                                      

      🌈个人主页:人不走空      

💖系列专栏:算法专题

⏰诗词歌赋:斯是陋室,惟吾德馨

 

da14e5cf865a427ea959fca470d8245a.gif

0892612a1c974a15aee1810997f71951.png 

目录

      🌈个人主页:人不走空      

💖系列专栏:算法专题

⏰诗词歌赋:斯是陋室,惟吾德馨

概述:

关键概念:

使用案例 :

摘要:

作者其他作品:


概述:


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

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

统计学:执行统计操作。

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

 


作者其他作品:

【Java】Spring循环依赖:原因与解决方法

OpenAI Sora来了,视频生成领域的GPT-4时代来了

[Java·算法·简单] LeetCode 14. 最长公共前缀 详细解读

【Java】深入理解Java中的static关键字

[Java·算法·简单] LeetCode 28. 找出字a符串中第一个匹配项的下标 详细解读

了解 Java 中的 AtomicInteger 类

算法题 — 整数转二进制,查找其中1的数量

深入理解MySQL事务特性:保证数据完整性与一致性

Java企业应用软件系统架构演变史