I have a list of subscriptions
subscriptions = [
{
code : "Heloo",
value:"some value",
reason : "some reason"
},
{
code : "Byeee",
value:"some byee",
reason : "some byee"
},
{
code : "World",
value:"some World",
reason : "some world"
}
]
I have another list of unsubscriptions:
unsubscribe : ["Heloo","World"]
I want to unsubscribe elements in the subscriptions by comparing these two arrays
Final Result :
subscriptions = [
{
code : "Byeee",
value:"some byee value",
reason : "some byee reason"
}
]
Below is my solution :
List<String> newList = new ArrayList<>();
for (String products : subscriptions) {
newList.add(products.code);
}
if (!newList.containsAll(unsubscribe) {
log.error("Few products are not subscribed");
}
for (int i = 0; i < subscriptions.size(); i++) {
if(unsubscribe.contains(subscriptions.get(i).code)) {
subscriptions.remove(i);
}
}
This could be better . I am looking for a better/optimized solution.
Using removeIf
will clean up your code considerably:
List<Subscription> subscriptions = ... ;
List<String> unsubscribe = ...;
subscriptions.removeIf(s -> unsubscribe.contains(s.code));
You can also do it with streams:
List<String> newList = subscriptions
.stream()
.filter(it -> !unsubscribe.contains(it.code))
.collect(Collectors.toList());
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.