I am trying to implement a simple method using Generics that first finds all records of specific type from repository, then we call getId() method to collect the ids and then print all ids for that type.
I want to call that function for different types such as Fruits/Vegetables/Drinks
My sample code works for a single type but I am struggling to use Generics in the second method, so that I can use it for any type instead of just Fruit. Can someone please point me in the right direction?
void audit() {
printObjectIds(frutisRepository.findAll, Fruit::Id, "Fruits")
printObjectIds(vegetablesRepository.findAll, Vegetable::Id, "Vegetables")
printObjectIds(drinksRepository.findAll, Drink::Id, "Drinks")
}
void printObjectIds(Supplier<List<Fruit>> supplier, Function<Fruit, Integer> function, String type) {
List<Integer> objectIds = supplier.get()
.stream()
.map(function)
.toList();
log.info("Type: {}", code)
objectIds.forEach(id -> log.info("Items: {}", objectIds))
}
Thanks in advance
Tried the sample code attached and using type erasure but can't get it to work
Try it like this. You need to declare type parameter to the left of the method and include it in the method arguments. I used records to demo.
Your original method contents would work just fine as long as fields like code
etc are visible.
public class GenericMethod {
record Fruit(int Id) {}
record Vegetable(int Id) {}
record Drink(int Id) {}
public static void main(String[] args) {
List<Fruit> fruits = List.of(new Fruit(20), new Fruit(30));
List<Vegetable> vegetables = List.of(new Vegetable(100), new Vegetable(200));
List<Drink> drinks = List.of(new Drink(2000), new Drink(3000));
printObjectIds(()->fruits, Fruit::Id, "Fruits");
printObjectIds(()->vegetables, Vegetable::Id, "Vegetables");
printObjectIds(()->drinks, Drink::Id, "Drinks");
}
static <T> void printObjectIds(Supplier<List<T>> supplier, Function<T, Integer> function, String type) {
List<Integer> objectIds = supplier.get()
.stream()
.map(function)
.toList();
System.out.println(objectIds);
}
}
prints
[20, 30]
[100, 200]
[2000, 3000]