Using generics for similar methods

Odhran Roche :

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());
}
Jorn Vernee :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=72692&siteId=1