javafunctiongenericstyped

Is there any way to make this typified method generic?


I'm trying to write a method which takes any collection of any type, two functions and two integer values which represent a certain limit.

For a better understanding i will show an example method which i would like to build generic.

private void buildSums() {
    double sum = 0;
    for (YearlyLineValuesEntity y_l_v_E : yearlyList) {
        if (y_l_v_E.getDb() >= 20001 && y_l_v_E.getDb() <= 20155) {
            sum += y_l_v_E.getAmount();
        }
    }
}

The return value in the example method is not important in this case. Only serves for a basic understanding of what my goal is.

This is my attempt:

The numbers in the if statement above are represent by the parameters "from" and "to" in the following method i´ve tried. getDb() should come from the parameter "propertyDb" and getAmount() should come from "propertyAmount"-paramater.

    <T> List <Double> sumUpGroup(Collection<? extends T> entityList, Function<? super T, Integer> propertyDb, Function<?
        super T, Double> propertyAmount, int from, int to) {
    Double sum = null;
    List<Double> list = null;
    for (int i = 0; i < entityList.size(); i++) {
        EntityList x = entityList.get(i); //generic type
        if (x.getDB() >= from && x.getDB() <= to) { //propertyDb here
            sum += x.getAmount(); //propertyAmount here
        }
    }
    list.add(sum);
    return list;
}

I don't know how to proceed further in the code with the 2 functions that come as parameters in the method. Do I need another method to take care of this?

do any of you have any ideas? Thanks


Solution

  • Something like the following would work (I removed the list stuff for clarity)

    <T> double sumUpGroup(Collection<? extends T> entityList, 
        Function<? super T, Integer> dbAccessor, 
        Function<? super T, Double> amountAccessor, 
        int from, int to) {
    
        double sum = 0;
        for (T entity : entityList) {
            int value = dbAccessor.apply(entity);
            if (value >= from && value <= to) {
                sum += amountAccessor.apply(entity);
            }
        }
    
        return sum;
    }
    

    You cand then call the method as follows, with the correct method names given of course

    sumUpGroup(myEntities, Entity::getDbValue, Entity::getAmount, 0, 100);