Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using generics for similar methods

Tags:

java

generics

These two Java methods are very similar but I'm not sure how I can do code reuse. I tried creating a generic object <T> but it's not allowed because of the constructor. Can I use generics here? Or should Event and Hotel have a parent? I'm not sure if I can use an Interface here.

private List<Event> extractEvents(List<String> eventList) {
    return eventList.stream()
                    .map(eventName -> new Event(eventName))
                    .collect(Collectors.toList());
}

private List<Hotel> extractHotels(List<String> hotelList) {
    return hotelList.stream()
                    .map(hotelName -> new Hotel(hotelName))
                    .collect(Collectors.toList());
}
like image 506
Odhran Roche Avatar asked Dec 24 '22 05:12

Odhran Roche


1 Answers

You could pass in the mapper separately:

private <T> List<T> extract(List<String> list, Function<String, T> mapper) {
    return list.stream()
               .map(mapper)
               .collect(Collectors.toList());
}
List<Event> r1 = extract(eventList, Event::new);
List<Hotel> r2 = extract(hotelList, Hotel::new);
like image 90
Jorn Vernee Avatar answered Jan 14 '23 05:01

Jorn Vernee