Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
stream

What is Stream.mapToLong method in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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 ToLongFunction here.

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 longs
List<Long> longList = new ArrayList<>();
longList.add(10L);
longList.add(4323L);
longList.add(8987L);
// Define the implementation of ToLongFunction interface
ToLongFunction<Long> multiplyByTwo = e -> e * 2;
// apply the multiplyByTwo using mapToLong function and print each value
longList.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 long values and add different values to the list.
  • Line 15: We define the implementation of ToLongFunction interface. We call multiplyByTwo where we multiply the input long value by 2.
  • Line 15: We apply the multiplyByTwo using mapToLong function and print the result.

RELATED TAGS

java
communitycreator
stream

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring