r/javahelp • u/stamangu • Sep 19 '20
Remove a List of items from a List?
Let's say you have
OrderA { int id; ..... }
OrderB { int id; ..... }
(orderA & orderB are different types)
List<OrderA> ordersA... List<OrderB> ordersB...
Is it possible to take out ordersB from ordersA where the id's match in an elegant way with streams? Something like:
ordersA.stream().filter(...some magic...).collect(...
7
u/Roachmeister Java Dev Sep 19 '20
I think that since they are different types you can't really do it with streams, at least not in one pass. However, you could first build a Set of all IDs in ordersB:
List<String> ids = ordersB.stream()
.map(OrderB::getId)
.collect(Collectors.toSet());And then you can filter ordersA by that set:
List<OrderA> filtered = ordersA.stream()
.filter(o -> !ids.contains(o.getId()))
.collect(Collectors.toList());3
u/stamangu Sep 20 '20
This is what i was looking for, thank you, and thanx to u/solonovamax and u/Yithar
Was trying to find a oneliner, but this is clean and fast readable.Thank you!
1
u/solonovamax Sep 21 '20
No problem. In reality, the solution I proposed is a clean one-liner because the IDE will spaces things out and make it nice to read.
Streams are very powerful (and fun to use!), so I'd really recommend you learn them at some point. Need to loop through a list to perform some operation? Use a stream, and slowly learn the API.
(Also, my original comment was incorrect about the time complexity and I've updated it to be correct.)
2
u/solonovamax Sep 19 '20 edited Sep 21 '20
An alternative would be using
List<OrderA> filtered = ordersA.stream().filter( o -> { ordersB.stream().anyMatch(o2 -> o.getId().equals(o2.getId())) });
But then it'd be O(n2) instead of O(n), because you're looping throughordersBfor every time ofordersA.Edit: actually I'm brain dead and both are O(n2 ) because worst case is O(n*m) where n=m, so O(n2 ). It's just that my version is doing an extra operation per loop, but they're still both looping twice, so the time complexity is the same.(Code might be wrong; I'm on mobile. Also, mobile formatting do be kinda shit.)
1
u/klata Sep 19 '20
Can’t you have one list with both of them?
1
u/stamangu Sep 20 '20
No, ordersA is my managed list of items while ordersB comes from an external system that do certain operations on the item i have tracked on my list ordersA.
One operation is to delete the items in ordersA that comes from the external system ordersB.
2
u/Yithar Intermediate Brewer Sep 19 '20
I would convert OrderB to a HashSet, only because otherwise filter() will have to iterate over the whole OrderB list for every OrderA element which is inefficient. So assuming we now have a HashSet<Integer>, we can do the folllowing:
ordersA.stream().filter(x -> !hashSet.contains(x.id)).collect(Collectors.toList())
Keep in mind things like filter() create a new Stream so it requires extra memory.
7
u/SpoilerAlertsAhead Extreme Brewer:hamster: Sep 19 '20
Look at Collections removeAll.