1

Is it possible to make a method or function in Java which could take List<T> where T can also be a List<V>... and so on until finally T is Integer and we have List<Integer> which gets converted to a List<Double>?

For example, List<Integer> gets converted into List<Double> and List<List<Integer>> gets converted into List<List<Double>>, etc.

dan dan
  • 345
  • 1
  • 2
  • 9

1 Answers1

1

Could be a recursive function which checks type T of List<T>. Recursion stops once the type is not inherited from List. Then use streams.

UPDATE

On a second thought, it looks like due to type erasure in Java it is not possible.

My original idea was to use a code like below. It's not prefect (nasty casts) but it is syntactically correct, however it looks like there is no syntactically correct way to call those functions.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class App {

    private <T> List<Double> foo(List<T> some) {
        return some.stream().map(item -> Double.class.cast(item)).collect(Collectors.toList());
    }

    private <T> List foo(List<T> some, Class<T> klass) {
        if (List.class.isAssignableFrom(klass)) {
            List result = new ArrayList<>();
            for (T item : some) {
                result.add(foo(List.class.cast(item), item.getClass()));
            }
            return result;
        } else {
            return foo(some);
        }
    }
}
scrutari
  • 1,058
  • 1
  • 15
  • 24