GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Java LongFunction Interface - Complete Tutorial with Examples Java LongFunction InterfaceLast modified: April 16, 2025
The
LongFunction Interface Overview
@FunctionalInterface
public interface LongFunction<R> {
R apply(long value);
}
The code above shows the structure of Basic LongFunction UsageThe simplest way to use LongFunction is with lambda expressions. We define how to transform the long input to output in the apply method. The example converts long values to their string representations. Main.java
package com.zetcode;
import java.util.function.LongFunction;
public class Main {
public static void main(String[] args) {
// Define a function that takes long and returns String
LongFunction<String> toStringFunction = l -> "Value: " + l;
// Apply the function
System.out.println(toStringFunction.apply(100L));
System.out.println(toStringFunction.apply(9999999999L));
// Function using static method reference
LongFunction<String> hexFunction = Long::toHexString;
System.out.println("Hex: " + hexFunction.apply(255L));
}
}
This example demonstrates basic LongFunction usage with lambda and method reference. The toStringFunction takes long and returns String. We apply it to different long values. Method reference provides concise syntax for existing methods. LongFunction with Mathematical OperationsLongFunction is useful for mathematical operations that take long values. We can perform calculations and return results of any type. This example calculates square roots and returns formatted strings. Main.java
package com.zetcode;
import java.util.function.LongFunction;
public class Main {
public static void main(String[] args) {
// Calculate square root and format as string
LongFunction<String> sqrtFunction = l -> {
double result = Math.sqrt(l);
return String.format("√%d = %.2f", l, result);
};
System.out.println(sqrtFunction.apply(25L));
System.out.println(sqrtFunction.apply(10000L));
System.out.println(sqrtFunction.apply(2L));
}
}
This example shows LongFunction performing mathematical operations. We calculate square roots of long values and format the results as strings. The function combines computation with string formatting. LongFunction with CollectionsLongFunction can generate collections based on long input. This example creates lists with repeated values. The size of the list is determined by the input. Main.java
package com.zetcode;
import java.util.function.LongFunction;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Create list with n copies of "Hello"
LongFunction<List<String>> listCreator = n ->
Collections.nCopies((int) n, "Hello");
System.out.println("Size 3: " + listCreator.apply(3L));
System.out.println("Size 5: " + listCreator.apply(5L));
// Note: casting long to int may lose precision for very large values
}
}
This example demonstrates LongFunction creating collections. We generate lists containing multiple copies of a string. The size is controlled by the long input. Be cautious with large values when casting to int. LongFunction with StreamsLongFunction works well with Java Streams for processing numeric data. This example uses it in a stream pipeline to transform long values. We convert numbers to their binary representations. Main.java
package com.zetcode;
import java.util.function.LongFunction;
import java.util.stream.LongStream;
public class Main {
public static void main(String[] args) {
// Function to convert long to binary string
LongFunction<String> toBinary = l -> Long.toBinaryString(l);
// Process stream of long values
LongStream.range(1, 6)
.mapToObj(toBinary)
.forEach(s -> System.out.println("Binary: " + s));
}
}
This example shows LongFunction in a stream pipeline. We convert a range of long values to their binary string representations. The mapToObj method accepts our LongFunction to perform the transformation. LongFunction with Exception HandlingLongFunction implementations may need to handle exceptions. This example shows how to deal with potential exceptions when processing long values. We validate input before processing. Main.java
package com.zetcode;
import java.util.function.LongFunction;
public class Main {
public static void main(String[] args) {
// Function with input validation
LongFunction<String> safeConverter = l -> {
if (l < 0) {
return "Error: Negative value";
}
return "Processed: " + (l * 2);
};
System.out.println(safeConverter.apply(10L));
System.out.println(safeConverter.apply(-5L));
System.out.println(safeConverter.apply(0L));
}
}
This example demonstrates exception handling in LongFunction. We validate the input long value before processing. For negative numbers, we return an error message instead of processing. This prevents potential issues. LongFunction with Custom ObjectsLongFunction can return custom objects based on long input. This example creates simple Point objects from long values. The x and y coordinates are derived from the input. Main.java
package com.zetcode;
import java.util.function.LongFunction;
class Point {
private final long x;
private final long y;
public Point(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return String.format("Point(%d, %d)", x, y);
}
}
public class Main {
public static void main(String[] args) {
// Create Point from long value
LongFunction<Point> pointCreator = l -> new Point(l, l * 2);
System.out.println(pointCreator.apply(5L));
System.out.println(pointCreator.apply(10L));
}
}
This example shows LongFunction creating custom Point objects. The function takes a long value and returns a Point with coordinates based on that value. This demonstrates how LongFunction can generate complex return types. Combining LongFunction with Other Functional InterfacesLongFunction can be combined with other functional interfaces for more complex operations. This example shows how to use it with Predicate for filtering. We process only even numbers. Main.java
package com.zetcode;
import java.util.function.LongFunction;
import java.util.function.LongPredicate;
public class Main {
public static void main(String[] args) {
// Predicate to check if even
LongPredicate isEven = l -> l % 2 == 0;
// Function to process even numbers
LongFunction<String> evenProcessor = l ->
isEven.test(l) ? "Even: " + l : "Odd: " + l;
System.out.println(evenProcessor.apply(4L));
System.out.println(evenProcessor.apply(7L));
}
}
This example combines LongFunction with LongPredicate. We first check if the input is even using the predicate. The function then processes the value differently based on the check. This shows functional composition. SourceJava LongFunction Interface Documentation In this article, we've covered the essential methods and features of the Java LongFunction interface. Understanding these concepts is crucial for functional programming with primitive long values in Java applications. AuthorMy name is Jan Bodnar, and I am a dedicated programmer with many years of experience in the field. I began writing programming articles in 2007 and have since authored over 1,400 articles and eight e-books. With more than eight years of teaching experience, I am committed to sharing my knowledge and helping others master programming concepts. List all Java tutorials. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |