What is Stream.mapToLong method in Java?
Overview
mapToLong() of the Stream interface is used to return a LongStream that contains the results of applying the provided implementation of ToLongFunction function on the stream’s items.
Note: You can read more about
ToLongFunctionhere.
Syntax
LongStream mapToInt(ToLongFunction<? super T> mapper)
Parameters
ToLongFunction<? super T> mapper: The mapper function to apply.
Return value
This method returns a new stream.
Code
import java.util.ArrayList;import java.util.List;import java.util.function.ToLongFunction;public class Main{public static void main(String[] args) {// define the list of longsList<Long> longList = new ArrayList<>();longList.add(10L);longList.add(4323L);longList.add(8987L);// Define the implementation of ToLongFunction interfaceToLongFunction<Long> multiplyByTwo = e -> e * 2;// apply the multiplyByTwo using mapToLong function and print each valuelongList.stream().mapToLong(multiplyByTwo).forEach(System.out::println);}}
Explanation
- Lines 1–3: We import the relevant packages.
- Lines 9–12: We define a list that can contain
longvalues and add different values to the list. - Line 15: We define the implementation of
ToLongFunctioninterface. We callmultiplyByTwowhere we multiply the inputlongvalue by2. - Line 15: We apply the
multiplyByTwousingmapToLongfunction and print the result.