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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With