How the Java Stream API makes your code better
前言
Java Stream 是一种强大的数据处理工具,可以帮助开发人员快速高效地处理和转换数据流。使用 Stream 操作可以大大简化代码,使其更具可读性和可维护性,从而提高开发效率。
filter():根据指定的 Predicate 保留符合条件的元素。
map():根据指定的 Function 映射每个元素,生成一个新的 Stream。
flatMap():将每个元素映射为一个 Stream,然后将这些 Stream 连接成一个 Stream。
distinct():返回一个去重后的 Stream。
sorted():对 Stream 进行排序。
peek():对每个元素执行指定的操作,但并不消费元素。
limit():返回一个截断后的 Stream。
skip():返回一个跳过指定元素后的 Stream。
forEach():对每个元素执行指定的操作。
toArray():将 Stream 转换为数组。
示例
示例 1:使用 filter() 方法过滤奇数
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); List<Integer> evenNumbers = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); System.out.println("Even numbers: " + evenNumbers); } }
输出结果:
Even numbers: [2, 4, 6, 8, 10]
示例 2:使用 map() 方法将每个字符串转换为大写
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<String> words = Arrays.asList("hello", "world", "java", "stream"); List<String> capitalizedWords = words.stream() .map(String::toUpperCase) .collect(Collectors.toList()); System.out.println("Capitalized words: " + capitalizedWords); } }
输出结果:
Capitalized words: [HELLO, WORLD, JAVA, STREAM]
示例 3:使用 flatMap() 方法将嵌套的列表展平为一个列表
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<List<Integer>> nestedNumbers = Arrays.asList( Arrays.asList(1, 2), Arrays.asList(3, 4, 5), Arrays.asList(6, 7, 8, 9) ); List<Integer> flattenedNumbers = nestedNumbers.stream() .flatMap(List::stream) .collect(Collectors.toList()); System.out.println("Flattened numbers: " + flattenedNumbers); } }
输出结果:
Flattened numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9]
示例 4:使用 distinct() 方法去除重复元素
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 2, 1, 4, 5, 4, 3, 6); List<Integer> distinctNumbers = numbers.stream() .distinct() .collect(Collectors.toList()); System.out.println("Distinct numbers: " + distinctNumbers); } }
输出结果:
Distinct numbers: [1, 2, 3, 4, 5, 6]
示例 5:使用 sorted() 方法对 Stream 进行排序
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(5, 3, 8, 2, 9, 1, 7, 4, 6, 10); List<Integer> sortedNumbers = numbers.stream() .sorted() .collect(Collectors.toList()); System.out.println("Sorted numbers: " + sortedNumbers); } }
输出结果:
Sorted numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
示例 6:使用 peek() 方法打印每个元素并统计元素个数
import java.util.Arrays; import java.util.List; public class Example { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); int count = numbers.stream() .peek(System.out::println) .mapToInt(Integer::intValue) .sum(); System.out.println("Total count: " + count); } }
输出结果:
1
2
3
4
5
6
7
8
9
10
Total count: 55
示例 7:使用 limit() 方法限制结果集大小
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); List<Integer> limitedNumbers = numbers.stream() .limit(5) .collect(Collectors.toList()); System.out.println("Limited numbers: " + limitedNumbers); } }
输出结果:
Limited numbers: [1, 2, 3, 4, 5]
示例 8:使用 skip() 方法跳过前面的元素
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); List<Integer> skippedNumbers = numbers.stream() .skip(5) .collect(Collectors.toList()); System.out.println("Skipped numbers: " + skippedNumbers); } }
输出结果:
Skipped numbers: [6, 7, 8, 9, 10]
示例 9:使用 forEach() 方法打印每个元素
import java.util.Arrays; import java.util.List; public class Example { public static void main(String[] args) { List<String> words = Arrays.asList("hello", "world", "java", "stream"); words.stream() .forEach(System.out::println); } }
输出结果:
hello
world
java
stream
示例 10:使用 toArray() 方法将 Stream 转换为数组
import java.util.Arrays; import java.util.List; public class Example { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Integer[] numberArray = numbers.stream() .toArray(Integer[]::new); System.out.println("Number array: " + Arrays.toString(numberArray)); } }
输出结果:
Number array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The above is the detailed content of How the Java Stream API makes your code better. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
