Sobes.tech
Middle

What are functional interfaces like Function<T, R>, DoubleFunction<R>, IntFunction<R>, and LongFunction<R> used for in Java?

sobes.tech AI

Answer from AI

These interfaces are used to represent operations that accept one argument and return a result.

  • Function<T, R>: Represents a function that accepts an argument of type T and returns a result of type R.

    // Example of using Function<String, Integer>
    Function<String, Integer> stringLength = s -> s.length();
    int length = stringLength.apply("Hello"); // Result: 5
    
  • DoubleFunction<R>: Represents a function that accepts an argument of type double and returns a result of type R.

    // Example of using DoubleFunction<String>
    DoubleFunction<String> numberToString = d -> "Number: " + d;
    String text = numberToString.apply(3.14); // Result: "Number: 3.14"
    
  • IntFunction<R>: Represents a function that accepts an argument of type int and returns a result of type R.

    // Example of using IntFunction<List<Integer>>
    IntFunction<List<Integer>> createList = size -> {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            list.add(i);
        }
        return list;
    };
    List<Integer> numbers = createList.apply(5); // Result: [0, 1, 2, 3, 4]
    
  • LongFunction<R>: Represents a function that accepts an argument of type long and returns a result of type R.

    // Example of using LongFunction<Date>
    LongFunction<Date> timestampToDate = timestamp -> new Date(timestamp);
    Date date = timestampToDate.apply(System.currentTimeMillis()); // Result: current date
    

These specialized interfaces (DoubleFunction, IntFunction, LongFunction) are used to avoid autoboxing when working with primitive types, which can improve performance.

What are functional interfaces like Function<T, R>… - sobes.tech