简体   繁体   中英

Using generics for similar methods

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM