1

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.

4
  • 1
    It's readable and it works. How many subscription do you need to handle that you think you need something more optimized? Commented Aug 28, 2020 at 10:06
  • You could try removeIf(...)... Commented Aug 28, 2020 at 10:07
  • @VishwaRatna First of all, please calm down. Second, OP didn't ask about any of those in particular. Those are in the answers, not in the question. Also, generics are used in the question. Should we add a java-5 tag as well? Commented Aug 28, 2020 at 10:37
  • @Federico klez Culloca : I have created an array new list of just the codes to check if newList contains all the items to unsubscribe. Could this be done in a better way instead of creating a new list ? Commented Aug 28, 2020 at 10:53

2 Answers 2

3

Using removeIf will clean up your code considerably:

List<Subscription> subscriptions =  ... ;
List<String> unsubscribe = ...;

subscriptions.removeIf(s -> unsubscribe.contains(s.code));
Sign up to request clarification or add additional context in comments.

Comments

0

You can also do it with streams:

List<String> newList = subscriptions
                                 .stream()
                                 .filter(it -> !unsubscribe.contains(it.code))
                                 .collect(Collectors.toList());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.