0

I have an object with data with some fields that are per part, but some fields that are per condition, per part (data that is per condition is in a subclass 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;
        }
    }
}

I need to write a lambda function that will return the data when the part/condition is applied:

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);
}

How do you apply two variables in a lambda function?

ryvantage
  • 13,064
  • 15
  • 63
  • 112

1 Answers1

1

As I was asking the question, I searched for "two argument java lambda function" and found this SO question: Can a java lambda have more than 1 parameter?

So, I created a BiFunction class:

@FunctionalInterface
interface BiFunction<One, Two, Three> {
    public Three apply(One one, Two two);
}

That applies One and Two and returns Three

And wrote the methods like so:

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);
}

And this works

ryvantage
  • 13,064
  • 15
  • 63
  • 112