前言
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!

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages such as Python and JavaScript to enhance cross-language interoperability.

Java's strong typed system ensures platform independence through type safety, unified type conversion and polymorphism. 1) Type safety performs type checking at compile time to avoid runtime errors; 2) Unified type conversion rules are consistent across all platforms; 3) Polymorphism and interface mechanisms make the code behave consistently on different platforms.

JNI will destroy Java's platform independence. 1) JNI requires local libraries for a specific platform, 2) local code needs to be compiled and linked on the target platform, 3) Different versions of the operating system or JVM may require different local library versions, 4) local code may introduce security vulnerabilities or cause program crashes.

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages for performance.

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version
