1

As far as I know Java 8 introduces a new method available for Collection types: removeif(). It accepts a predicate which defines the condition on which the elements should be removed. It returns a boolean where a true response means that at least one item has been removed and false otherwise: I have this class:

HotelPriceSummary {
     Hotel hotel;
     float price
}

a List<HotelPriceSummary> allHotels;

and Iterable<Hotel> discardedHotels

I would like to do something like (obviously existsIn is a functions that does not exist, is to express what I would like to do but I didn't find the way)

allHotels.removeIf(h -> h.getHotel().existsIn (discardedHotels))
Nuñito Calzada
  • 4,394
  • 47
  • 174
  • 301

1 Answers1

8

You can't efficiently locate an item in an Iterable. I would suggest copying it to a temporary set (unless it already is a set) and then calling contains():

Set<Hotel> discardedSet = new HashSet<>();
discardedHotels.forEach(discardedSet::add);
allHotels.removeIf(h -> discardedSet.contains(h.getHotel()));

If you don't mind the O(n*m) complexity, you can call List.removeIf() within Iterable.forEach():

discardedHotels.forEach(h -> allHotels.removeIf(hps -> hps.getHotel().equals(h)))
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • Set creation can be simplified by `Set discardedSet = StreamSupport.stream(discardedHotels.spliterator(), false).collect(Collectors.toSet());` – Flown Feb 28 '18 at 08:39
  • 3
    @Flown Thanks for the suggestion, but I don't see that as a simplification. – shmosel Feb 28 '18 at 08:41