Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<String> minus List<String>

Tags:

java

list

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;
    }

}
like image 998
user3127896 Avatar asked Jan 12 '23 10:01

user3127896


2 Answers

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);

like image 179
Hrishikesh Avatar answered Jan 13 '23 23:01

Hrishikesh


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.

like image 42
user2336315 Avatar answered Jan 13 '23 23:01

user2336315