user3127896
user3127896

Reputation: 6563

List<String> minus List<String>

I have following code. In the first i tried to set values in the list called 'unavailable'. Next, in the for each I have to produce a cycle on the list domainStr minus unavailable. How can i do it?

public Result execute(List<String> domainsStr) {

        Result result = new Result();       

        try {
            List<String> domains = domainService.findByNames(domainsStr);
            result.setUnavailable(domains);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        for (String domain : domainsStr) {
        ......
        }
        return result;
    }
    public static class Result {

    private List<String> unavailable = new ArrayList<>();


    public List<String> getUnavailable() {
        return unavailable;
    }

    public void setUnavailable(List<String> unavailable) {
        this.unavailable = unavailable;
    }

}

Upvotes: 4

Views: 907

Answers (3)

Dan Temple
Dan Temple

Reputation: 2764

List<String> tempList = new ArrayList<String>(domainsStr);
tempList.removeAll(result.getUnavailable());
for(String domain : tempList){ 
    .....

I put them into a tempt list so you don't lose the items in the domainsStr list.

Upvotes: 1

Hrishikesh
Hrishikesh

Reputation: 2053

removeAll(Collection c) is the function which would be the most helpful to you. Having said that, this will work properly only if you have the equals method correctly defined for your Domain object. In this case it is a String so it doesnt matter. But, just to keep it in mind.

so just say, domainsStr.removeAll(result.getUnavailable());

Also, if the Result class is static, why the new object creation here?

Result result = new Result();

This result.setUnavailable(domains); can be changed to Result.setUnavailable(domains);

Upvotes: 7

user2336315
user2336315

Reputation: 16067

I have to to produce a cycle on the list domainStr minus unavailable.

If I understood correctly, I think you are looking for the removeAll method :

Removes from this list all of its elements that are contained in the specified collection (optional operation).

domainsStr.removeAll(result.getUnavailable());
for (String domain : domainsStr) {

}

If you want to let domainsStr unchanged, you can create a temporary list and perfom these operations on it.

Upvotes: 1

Related Questions