list.stream()
时间: 2023-11-12 09:09:21 浏览: 73
hosts.stream
List.stream() is a method in Java 8 that returns a Stream object containing the elements of the list. A Stream is a sequence of elements that can be processed in parallel or sequentially.
Using the stream() method allows us to perform many operations such as filtering, mapping, sorting, and reducing on the elements of the list. It also allows us to perform lazy evaluation, which means that the operations are only executed when needed, improving efficiency.
Here is an example of using the stream() method to find the sum of all even numbers in a list:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
System.out.println(sum); // Output: 30
In this example, we first create a list of integers. We then call the stream() method to get a Stream object. We then use the filter() method to filter out all the odd numbers, leaving only the even numbers. We then use the mapToInt() method to convert the Integer objects to primitive ints, and finally, we use the sum() method to find the sum of all the even numbers.
阅读全文