我有一个数据的对象,其中包含每个部分的一些字段,但每个部分的每个条件的某些字段(每个条件的数据都在子类PartData
中):
class Part {
// per part data
final String part_number;
public Part(String part_number) {
this.part_number = part_number;
condition_id_to_data = new HashMap<>();
}
public String getPart_number() {
return part_number;
}
Map<Integer, PartData> condition_id_to_data;
public PartData getData(int condition_id) {
return condition_id_to_data.get(condition_id);
}
// per condition data
class PartData {
final int condition_id;
public PartData(int condition_id) {
this.condition_id = condition_id;
}
BigDecimal sales;
BigDecimal quotes;
public BigDecimal getQuotes() {
return quotes;
}
public BigDecimal getSales() {
return sales;
}
}
}
我需要编写一个lambda函数,它将在应用part / condition时返回数据:
Function<Part, String> part_number_function;
Function<Part, Function<Integer, BigDecimal>> sales_function;
Function<Part, Function<Integer, BigDecimal>> quotes_function;
void go() {
Part part = ...;
int condition_id = ...;
part_number_function = Part::getPart_number; // Got this part
String part_number = part_number_function.apply(part); // works
sales_function = Part::getData ... ?
quotes_function = Part::getData ... ?
BigDecimal sales = sales_function.apply(part).apply(condition_id);
BigDecimal quotes = quotes_function.apply(part).apply(condition_id);
}
如何在lambda函数中应用两个变量?
答案 0 :(得分:1)
当我问这个问题时,我搜索了“两个参数java lambda函数”并找到了这个问题:Can a java lambda have more than 1 parameter?
所以,我创建了一个BiFunction
类:
@FunctionalInterface
interface BiFunction<One, Two, Three> {
public Three apply(One one, Two two);
}
这适用于One
和Two
并返回Three
并编写了这样的方法:
Function<Part, String> part_number_function;
BiFunction<Part, Integer, BigDecimal> sales_function;
BiFunction<Part, Integer, BigDecimal> quotes_function;
void go() {
Part part = ...;
int condition_id = ...;
part_number_function = a_part -> a_part.getPart_number();
sales_function = (a_part, b_cond) -> a_part.getData(b_cond).sales;
quotes_function = (a_part, b_cond) -> a_part.getData(b_cond).quotes;
String part_number = part_number_function.apply(part);
BigDecimal sales = sales_function.apply(part, condition_id);
BigDecimal quotes = quotes_function.apply(part, condition_id);
}
这有效