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 ObjLongConsumer Interface - Complete Tutorial with Examples Java ObjLongConsumer InterfaceLast modified: April 16, 2025
The
ObjLongConsumer Interface Overview
@FunctionalInterface
public interface ObjLongConsumer<T> {
void accept(T t, long value);
}
The code above shows the structure of Basic ObjLongConsumer UsageThe simplest way to use ObjLongConsumer is with lambda expressions. We define how to process the object and long parameters in the accept method. This example shows a consumer that logs product updates. Main.java
package com.zetcode;
import java.util.function.ObjLongConsumer;
public class Main {
public static void main(String[] args) {
// Define a consumer for product updates
ObjLongConsumer<String> productUpdater = (name, newStock) -> {
System.out.printf("Updating product '%s' with new stock: %d%n",
name, newStock);
};
// Use the consumer
productUpdater.accept("Laptop", 150L);
productUpdater.accept("Smartphone", 300L);
}
}
This example demonstrates basic ObjLongConsumer with Collections
Main.java
package com.zetcode;
import java.util.HashMap;
import java.util.Map;
import java.util.function.ObjLongConsumer;
public class Main {
public static void main(String[] args) {
Map<String, Long> inventory = new HashMap<>();
inventory.put("Keyboard", 50L);
inventory.put("Mouse", 75L);
inventory.put("Monitor", 30L);
// Consumer to update inventory
ObjLongConsumer<String> inventoryUpdater = (product, quantity) -> {
inventory.merge(product, quantity, Long::sum);
};
// Apply updates
inventoryUpdater.accept("Keyboard", 20L);
inventoryUpdater.accept("Monitor", 15L);
inventoryUpdater.accept("Headphones", 40L); // New product
System.out.println("Updated inventory: " + inventory);
}
}
This example shows ObjLongConsumer with collections. The inventoryUpdater adds quantities to existing products or creates new entries. The Map.merge method handles both cases. This pattern is useful for bulk updates. ObjLongConsumer in Stream Processing
Main.java
package com.zetcode;
import java.util.List;
import java.util.function.ObjLongConsumer;
public class Main {
public static void main(String[] args) {
record OrderItem(String name, double price, int quantity) {}
List<OrderItem> orderItems = List.of(
new OrderItem("Shirt", 29.99, 2),
new OrderItem("Pants", 49.99, 1),
new OrderItem("Shoes", 89.99, 1)
);
// Consumer to calculate total price
ObjLongConsumer<OrderItem> priceCalculator = (item, total) -> {
double itemTotal = item.price() * item.quantity();
System.out.printf("%s: %.2f x %d = %.2f (Running total: %d)%n",
item.name(), item.price(), item.quantity(),
itemTotal, total + (long) itemTotal);
};
// Process with running total
long runningTotal = 0;
for (OrderItem item : orderItems) {
priceCalculator.accept(item, runningTotal);
runningTotal += (long) (item.price() * item.quantity());
}
}
}
This example demonstrates ObjLongConsumer in stream-like processing. The priceCalculator shows each item's total and the running sum. While not using Stream API directly, it shows the consumer pattern for sequential processing. ObjLongConsumer with Primitive Arrays
Main.java
package com.zetcode;
import java.util.function.ObjLongConsumer;
public class Main {
public static void main(String[] args) {
long[] temperatures = {22L, 24L, 19L, 21L, 25L};
String location = "New York";
// Consumer to process temperature readings
ObjLongConsumer<String> tempProcessor = (loc, temp) -> {
String condition = temp > 23 ? "Warm" :
temp < 20 ? "Cool" : "Mild";
System.out.printf("%s: %d°C (%s)%n", loc, temp, condition);
};
// Process all temperatures
for (long temp : temperatures) {
tempProcessor.accept(location, temp);
}
}
}
This example shows ObjLongConsumer with primitive arrays. The tempProcessor takes location context and temperature values. It categorizes each reading and prints a formatted message. The consumer handles both object and primitive. ObjLongConsumer for Object State Modification
Main.java
package com.zetcode;
import java.util.function.ObjLongConsumer;
public class Main {
static class BankAccount {
private String owner;
private long balance;
public BankAccount(String owner, long balance) {
this.owner = owner;
this.balance = balance;
}
public void processTransaction(ObjLongConsumer<BankAccount> operation,
long amount) {
operation.accept(this, amount);
}
@Override
public String toString() {
return owner + "'s account: $" + balance;
}
}
public static void main(String[] args) {
BankAccount account = new BankAccount("John", 1000L);
// Define deposit operation
ObjLongConsumer<BankAccount> deposit = (acc, amount) -> {
acc.balance += amount;
System.out.println("Deposited: $" + amount);
};
// Define withdrawal operation
ObjLongConsumer<BankAccount> withdraw = (acc, amount) -> {
if (acc.balance >= amount) {
acc.balance -= amount;
System.out.println("Withdrawn: $" + amount);
} else {
System.out.println("Insufficient funds for withdrawal: $" + amount);
}
};
// Process transactions
account.processTransaction(deposit, 500L);
System.out.println(account);
account.processTransaction(withdraw, 200L);
System.out.println(account);
account.processTransaction(withdraw, 2000L);
System.out.println(account);
}
}
This example demonstrates state modification with ObjLongConsumer in Method Parameters
Main.java
package com.zetcode;
import java.util.function.ObjLongConsumer;
public class Main {
static void processData(String[] items, long[] values,
ObjLongConsumer<String> processor) {
if (items.length != values.length) {
throw new IllegalArgumentException("Arrays must have equal length");
}
for (int i = 0; i < items.length; i++) {
processor.accept(items[i], values[i]);
}
}
public static void main(String[] args) {
String[] products = {"Tablet", "Laptop", "Phone"};
long[] sales = {1500L, 2300L, 3100L};
// Consumer to print product sales
ObjLongConsumer<String> salesReporter = (product, count) -> {
System.out.printf("%-10s: %5d units%n", product, count);
};
// Consumer to calculate revenue (assuming $500 per unit)
ObjLongConsumer<String> revenueCalculator = (product, count) -> {
long revenue = count * 500;
System.out.printf("%-10s: $%,d%n", product, revenue);
};
System.out.println("Sales Report:");
processData(products, sales, salesReporter);
System.out.println("\nRevenue Estimate:");
processData(products, sales, revenueCalculator);
}
}
This example shows ObjLongConsumer as method parameters. The processData method accepts any consumer for processing paired String and long values. Different consumers provide varied processing without modifying the core method. Combining ObjLongConsumer with Other Functional Interfaces
Main.java
package com.zetcode;
import java.util.function.ObjLongConsumer;
import java.util.function.LongPredicate;
public class Main {
public static void main(String[] args) {
record SensorReading(String sensorId, long value) {}
SensorReading[] readings = {
new SensorReading("TEMP-1", 22L),
new SensorReading("TEMP-2", 45L), // Invalid
new SensorReading("TEMP-3", 18L),
new SensorReading("TEMP-4", 50L) // Invalid
};
// Predicate to validate readings
LongPredicate isValid = value -> value >= 20L && value <= 30L;
// Consumer to process valid readings
ObjLongConsumer<String> readingProcessor = (id, value) -> {
System.out.printf("Processing valid reading - %s: %d%n", id, value);
// Additional processing logic here
};
// Process readings with filter
for (SensorReading reading : readings) {
if (isValid.test(reading.value())) {
readingProcessor.accept(reading.sensorId(), reading.value());
} else {
System.out.printf("Skipping invalid reading - %s: %d%n",
reading.sensorId(), reading.value());
}
}
}
}
This example combines ObjLongConsumer with LongPredicate. The isValid predicate filters readings before processing. The readingProcessor only receives valid values. This pattern enables clean separation of concerns. SourceJava ObjLongConsumer Interface Documentation In this article, we've covered the essential methods and features of the Java ObjLongConsumer interface. Understanding these concepts is crucial for handling operations that require both object and long primitive parameters efficiently. 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. |