Java 8嵌套Lambda函数实现:如何传递两个参数获取数据?
You're on the right track with the part_number_function! For sales_function and quotes_function, we need to create nested functions: first accept a Part, then return another function that takes a condition ID and returns the corresponding BigDecimal value. Here's how to implement this cleanly:
Using Nested Lambda Expressions (Most Readable)
This approach directly maps the chain of operations: retrieve the PartData for the given condition ID, then extract the sales/quotes value from it.
void go() { Part part = ...; int condition_id = ...; part_number_function = Part::getPart_number; String part_number = part_number_function.apply(part); // Define sales_function: Part -> (Integer -> BigDecimal) sales_function = partObj -> conditionId -> partObj.getData(conditionId).getSales(); // Define quotes_function using the same pattern quotes_function = partObj -> conditionId -> partObj.getData(conditionId).getQuotes(); BigDecimal sales = sales_function.apply(part).apply(condition_id); BigDecimal quotes = quotes_function.apply(part).apply(condition_id); }
Breakdown:
sales_functionis aFunction<Part, Function<Integer, BigDecimal>>:- Calling
sales_function.apply(part)returns aFunction<Integer, BigDecimal>bound to your specificpartinstance. - Calling
apply(condition_id)on that inner function usespart.getData(condition_id)to fetch thePartData, then callsgetSales()to get the final value.
- Calling
Alternative: Using Method References with andThen
If you prefer method references over nested lambdas, you can chain the getData call with the getter method using Function.andThen(). A cast is needed here to help the compiler infer the functional interface type:
void go() { Part part = ...; int condition_id = ...; part_number_function = Part::getPart_number; String part_number = part_number_function.apply(part); sales_function = partObj -> ((Function<Integer, PartData>) partObj::getData).andThen(PartData::getSales); quotes_function = partObj -> ((Function<Integer, PartData>) partObj::getData).andThen(PartData::getQuotes); BigDecimal sales = sales_function.apply(part).apply(condition_id); BigDecimal quotes = quotes_function.apply(part).apply(condition_id); }
Optional: Handle Null Values
If getData(condition_id) might return null, add a null check to avoid NullPointerException using Optional:
sales_function = partObj -> conditionId -> Optional.ofNullable(partObj.getData(conditionId)) .map(PartData::getSales) .orElse(BigDecimal.ZERO);
内容的提问来源于stack exchange,提问作者ryvantage

