Java mapToInt() Method: Convert Stream to IntStream
The 'mapToInt()' method is a method provided by the Java Stream API, which is used to convert a stream of objects into a stream of primitive integers. This method takes a function as a parameter, which is applied to each element of the stream to produce an integer value. The resulting stream of integers can then be further processed using other stream operations.
Here's an example of how to use the 'mapToInt()' method:
List<String> strings = Arrays.asList('1', '2', '3', '4', '5');
IntStream intStream = strings.stream().mapToInt(Integer::parseInt);
In this example, we have a list of strings that represent integer values. We use the 'stream()' method to create a stream of strings, and then we apply the 'mapToInt()' method to this stream to convert it into a stream of integers using the 'Integer::parseInt' method reference. The resulting 'IntStream' can then be used with other stream operations, such as 'sum()', 'average()', or 'forEach()'.
原文地址: https://www.cveoy.top/t/topic/oLld 著作权归作者所有。请勿转载和采集!