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 ToLongFunction Interface - Complete Tutorial with Examples Java ToLongFunction InterfaceLast modified: April 16, 2025
The
ToLongFunction Interface Overview
@FunctionalInterface
public interface ToLongFunction<T> {
long applyAsLong(T value);
}
The code above shows the simple structure of Basic ToLongFunction UsageThe simplest way to use ToLongFunction is with lambda expressions. We define how to convert input to long in the applyAsLong method. The example converts strings to their lengths as longs. Main.java
package com.zetcode;
import java.util.function.ToLongFunction;
public class Main {
public static void main(String[] args) {
// Define a function that takes String and returns its length as long
ToLongFunction<String> lengthFunction = s -> s.length();
// Apply the function
System.out.println("Length of 'hello': " + lengthFunction.applyAsLong("hello"));
System.out.println("Length of 'functional': " + lengthFunction.applyAsLong("functional"));
// Function using method reference
ToLongFunction<String> lengthMethodRef = String::length;
System.out.println("Length via method ref: " + lengthMethodRef.applyAsLong("method"));
}
}
This example demonstrates basic ToLongFunction usage with lambda and method reference. The lengthFunction takes String and returns primitive long. We apply it to different strings. Method reference provides concise syntax for existing methods. ToLongFunction with Custom Objects
Main.java
package com.zetcode;
import java.util.function.ToLongFunction;
class Employee {
private String name;
private long salary;
public Employee(String name, long salary) {
this.name = name;
this.salary = salary;
}
public long getSalary() { return salary; }
}
public class Main {
public static void main(String[] args) {
// Function to extract salary from Employee
ToLongFunction<Employee> salaryExtractor = Employee::getSalary;
Employee emp1 = new Employee("John", 75000L);
Employee emp2 = new Employee("Sarah", 85000L);
System.out.println("John's salary: " + salaryExtractor.applyAsLong(emp1));
System.out.println("Sarah's salary: " + salaryExtractor.applyAsLong(emp2));
}
}
This example shows ToLongFunction working with custom Employee objects. The salaryExtractor function uses method reference to get salary values. This pattern is common when processing object collections in numeric operations. ToLongFunction in Stream Operations
Main.java
package com.zetcode;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry", "date");
// Calculate total characters using mapToLong
long totalChars = words.stream()
.mapToLong(String::length)
.sum();
System.out.println("Total characters: " + totalChars);
// Calculate average word length
double avgLength = words.stream()
.mapToLong(String::length)
.average()
.orElse(0.0);
System.out.println("Average length: " + avgLength);
}
}
This example demonstrates ToLongFunction in Stream operations. We use method reference String::length as ToLongFunction. The mapToLong operation creates a LongStream for efficient numeric processing like sum and average. ToLongFunction with Primitive Arrays
Main.java
package com.zetcode;
import java.util.Arrays;
import java.util.function.ToLongFunction;
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
// Function to convert int to long (needed for large numbers)
ToLongFunction<Integer> intToLong = x -> (long) x;
// Process array using ToLongFunction
long sum = Arrays.stream(numbers)
.mapToLong(intToLong)
.sum();
System.out.println("Sum of array: " + sum);
// Another example: square each number
long[] squares = Arrays.stream(numbers)
.mapToLong(x -> (long) x * x)
.toArray();
System.out.println("Squares: " + Arrays.toString(squares));
}
}
This example shows ToLongFunction processing primitive arrays. We convert int values to longs to prevent overflow in calculations. The mapToLong operation enables efficient numeric transformations on array elements. Combining ToLongFunction with Other Functional Interfaces
Main.java
package com.zetcode;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.function.ToLongFunction;
public class Main {
public static void main(String[] args) {
List<String> products = Arrays.asList("Laptop:1200", "Mouse:25",
"Keyboard:45", "Monitor:300");
// Predicate to filter expensive products
Predicate<String> expensive = s -> {
long price = Long.parseLong(s.split(":")[1]);
return price > 100;
};
// ToLongFunction to extract price
ToLongFunction<String> priceExtractor = s ->
Long.parseLong(s.split(":")[1]);
// Calculate total of expensive products
long total = products.stream()
.filter(expensive)
.mapToLong(priceExtractor)
.sum();
System.out.println("Total expensive products: $" + total);
}
}
This example combines Predicate with ToLongFunction in a stream pipeline. We first filter expensive products, then extract prices as longs for summation. This shows how functional interfaces work together for data processing. ToLongFunction vs Function
While similar, Main.java
package com.zetcode;
import java.util.function.Function;
import java.util.function.ToLongFunction;
public class Main {
public static void main(String[] args) {
// ToLongFunction - returns primitive long
ToLongFunction<String> toLongFunc = s -> Long.parseLong(s);
long primitiveLong = toLongFunc.applyAsLong("123456789012");
// Function - returns Long object
Function<String, Long> func = s -> Long.parseLong(s);
Long objectLong = func.apply("123456789012");
System.out.println("ToLongFunction result: " + primitiveLong);
System.out.println("Function result: " + objectLong);
// Performance comparison
long start = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) {
toLongFunc.applyAsLong("123");
}
long toLongTime = System.nanoTime() - start;
start = System.nanoTime();
for (int i = 0; i < 1_000_000; i++) {
func.apply("123");
}
long funcTime = System.nanoTime() - start;
System.out.println("ToLongFunction time: " + toLongTime);
System.out.println("Function time: " + funcTime);
}
}
This example compares ToLongFunction and Function. Both parse strings to longs, but ToLongFunction avoids boxing overhead. The performance test shows ToLongFunction is faster for numeric operations due to primitive handling. Specialized ToLongFunction Variants
Java provides specialized variants of Main.java
package com.zetcode;
import java.util.function.DoubleToLongFunction;
import java.util.function.IntToLongFunction;
import java.util.function.LongUnaryOperator;
public class Main {
public static void main(String[] args) {
// IntToLongFunction example
IntToLongFunction square = x -> (long) x * x;
System.out.println("Square of 5: " + square.applyAsLong(5));
// DoubleToLongFunction example (rounding)
DoubleToLongFunction rounder = d -> Math.round(d);
System.out.println("Rounded 3.7: " + rounder.applyAsLong(3.7));
// LongUnaryOperator (special case of ToLongFunction)
LongUnaryOperator increment = x -> x + 1;
System.out.println("Incremented 10: " + increment.applyAsLong(10));
}
}
This example demonstrates specialized ToLongFunction variants. These interfaces accept primitive inputs directly, avoiding boxing overhead. They are useful for high-performance numeric processing in Java applications. SourceJava ToLongFunction Interface Documentation In this article, we've covered the essential methods and features of the Java ToLongFunction interface. Understanding these concepts is crucial for efficient numeric processing and functional programming 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. |