Collectors.mapToInt
时间: 2023-10-23 14:34:41 浏览: 101
Collectors.mapToInt is a static method in the Java Stream API that is used to perform a reduction operation on a stream of elements and collect the result as an IntStream. It allows you to convert a stream of objects to an IntStream by applying a mapping function to each element and then summing or reducing the resulting values.
Here's an example usage of Collectors.mapToInt:
```java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> numbers = Arrays.asList("1", "2", "3", "4", "5");
int sum = numbers.stream()
.mapToInt(Integer::parseInt)
.sum();
System.out.println("Sum: " + sum);
}
}
```
In this example, we have a list of strings representing numbers. We use `numbers.stream()` to create a stream of these strings. Then, we use `mapToInt(Integer::parseInt)` to convert each string to an integer value using the `parseInt` method from the `Integer` class. Finally, we call `sum()` to calculate the sum of all the integers in the stream.
The output will be:
```
Sum: 15
```
I hope this helps! Let me know if you have any further questions.
阅读全文