How to implement ToLongFunction<T> using lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

ToLongFunction<T> is a functional interface defined in java.util.function package. This functional interface accepts a reference type as input and produces a long-valued result. ToLongFunction<T> interface can be used as an assignment target for a lambda expression or method reference. It contains only one abstract method: applyAsLong().

Syntax

@FunctionalInterface
interface ToLongFunction<T> {
   long applyAsLong(T value);
}

Example

import java.util.*;
import java.util.function.ToLongFunction;

public class ToLongFunctionTest {
   public static void main(String args[]) {
      List<String> list = new ArrayList<String>();
      list.add("11");
      list.add("22");
      list.add("33");
      list.add("44");
      list.add("55");
      ToLongFunction<String> function = (String item) -> Long.valueOf(item);  // lambda expression
      list.stream().mapToLong(function).forEach(System.out::println);
   }
}

Output

11
22
33
44
55
raja
Published on 24-Jan-2020 12:05:58
Advertisements