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 LongConsumer Interface - Complete Tutorial with Examples Java LongConsumer InterfaceLast modified: April 16, 2025
The
LongConsumer Interface Overview
@FunctionalInterface
public interface LongConsumer {
void accept(long value);
default LongConsumer andThen(LongConsumer after);
}
The code above shows the structure of Basic LongConsumer UsageThe simplest way to use LongConsumer is with lambda expressions. We define what to do with the long value in the accept method. The example prints long values. Main.java
package com.zetcode;
import java.util.function.LongConsumer;
public class Main {
public static void main(String[] args) {
// Define a consumer that prints long values
LongConsumer printConsumer = value -> System.out.println("Value: " + value);
// Use the consumer
printConsumer.accept(42L);
printConsumer.accept(10000000000L);
// Consumer with method reference
LongConsumer sysOutConsumer = System.out::println;
sysOutConsumer.accept(999L);
}
}
This example demonstrates basic LongConsumer usage with lambda and method reference. The printConsumer takes a long value and prints it. We apply it to different values. Method reference provides concise syntax for existing methods. LongConsumer with andThen
The Main.java
package com.zetcode;
import java.util.function.LongConsumer;
public class Main {
public static void main(String[] args) {
// First consumer prints the value
LongConsumer printValue = value -> System.out.println("Original: " + value);
// Second consumer prints the squared value
LongConsumer printSquare = value ->
System.out.println("Squared: " + (value * value));
// Chain the consumers
LongConsumer combined = printValue.andThen(printSquare);
combined.accept(5L);
combined.accept(10L);
}
}
This example shows consumer chaining with LongConsumer with StreamsLongConsumer is commonly used with LongStream for processing primitive long values. The forEach terminal operation accepts a LongConsumer to perform side-effects. Main.java
package com.zetcode;
import java.util.stream.LongStream;
public class Main {
public static void main(String[] args) {
// Create a LongStream
LongStream.rangeClosed(1L, 5L)
// Filter even numbers
.filter(n -> n % 2 == 0)
// Use LongConsumer to print
.forEach(value -> {
System.out.println("Even value: " + value);
System.out.println("Cube: " + (value * value * value));
});
}
}
This example demonstrates LongConsumer usage in LongStream. We filter even numbers and use forEach with a consumer that prints the value and its cube. Streams provide clean data processing pipelines. Stateful LongConsumerLongConsumer can maintain state between invocations when implemented as a class or using an external variable. This allows accumulating values across multiple calls. Main.java
package com.zetcode;
import java.util.function.LongConsumer;
public class Main {
public static void main(String[] args) {
// Using an array to hold state (effectively final)
long[] sum = {0L};
// Consumer that accumulates values
LongConsumer summingConsumer = value -> sum[0] += value;
summingConsumer.accept(10L);
summingConsumer.accept(20L);
summingConsumer.accept(30L);
System.out.println("Total sum: " + sum[0]);
// Using a class implementation
class AveragingConsumer implements LongConsumer {
private long total = 0;
private int count = 0;
@Override
public void accept(long value) {
total += value;
count++;
}
public double getAverage() {
return count == 0 ? 0 : (double) total / count;
}
}
AveragingConsumer avgConsumer = new AveragingConsumer();
avgConsumer.accept(5L);
avgConsumer.accept(15L);
avgConsumer.accept(25L);
System.out.println("Average: " + avgConsumer.getAverage());
}
}
This example shows stateful LongConsumer implementations. The first uses an array to hold state in a lambda. The second uses a class to track total and count for calculating average. Both maintain state between accept calls. LongConsumer in CollectionsLongConsumer can be used with collections containing long values. We can process collections by converting them to streams or iterating directly. Main.java
package com.zetcode;
import java.util.Arrays;
import java.util.List;
import java.util.function.LongConsumer;
public class Main {
public static void main(String[] args) {
List<Long> numbers = Arrays.asList(100L, 200L, 300L, 400L);
// Consumer that formats and prints long values
LongConsumer formatter = value ->
System.out.printf("Formatted: $%,d%n", value);
// Process list with stream
numbers.stream()
.mapToLong(Long::longValue)
.forEach(formatter);
// Process array directly
long[] primitives = {1000L, 2000L, 3000L};
Arrays.stream(primitives)
.forEach(formatter.andThen(
v -> System.out.println("---")));
}
}
This example shows LongConsumer usage with collections. We process a List Combining LongConsumer with Other Functional InterfacesLongConsumer can be combined with other functional interfaces to create more complex operations. This demonstrates interoperability between functional types. Main.java
package com.zetcode;
import java.util.function.LongConsumer;
import java.util.function.LongFunction;
import java.util.function.LongPredicate;
public class Main {
public static void main(String[] args) {
// Predicate to filter negative numbers
LongPredicate isPositive = n -> n > 0;
// Function to convert long to String
LongFunction<String> toStringWithUnit = n -> n + " meters";
// Consumer to print processed values
LongConsumer printer = n ->
System.out.println("Processed: " + toStringWithUnit.apply(n));
// Process values
long[] values = {10, -5, 20, -3, 30};
for (long n : values) {
if (isPositive.test(n)) {
printer.accept(n);
}
}
// Using method that accepts LongConsumer
processValues(15L, 25L, printer.andThen(
n -> System.out.println("--- End of record ---")));
}
private static void processValues(long... values, LongConsumer consumer) {
for (long n : values) {
consumer.accept(n);
}
}
}
This example combines LongConsumer with LongPredicate and LongFunction. We filter positive numbers, convert them to strings with units, and print them. The example also shows passing LongConsumer to a method. SourceJava LongConsumer Interface Documentation In this article, we've covered the essential methods and features of the Java LongConsumer interface. Understanding these concepts is crucial for functional programming with primitive long values in modern 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. |