Jatin Gupta
Jatin Gupta

Reputation: 33

How can I check if String contains the domain name listed in ArrayList having multiple domains in Java?

I'm trying to allow request from specific domains only which are listed in ArrayList, so I need to put a conditional check if URL contains the domains listed in ArrayList then allow otherwise throw an Exception.

Suppose my ArrayList = [abc.com, def.com, xyz.com] I want to check if my URL contains any of these domains from ArrayList then return true else return false.

I tried below code, but it checks the domain name one by one. However, it returns false if domain name is valid -

ArrayList = [abc.com, def.com, xyz.com]

public static boolean isListContainValidDomain(List<String> arraylist) {
String reqURL = "dev.def.com";
boolean isValid = true;

    for (String str : arraylist) {

        if(!reqURL.contains(str.toLowerCase())){
            isValid = false;
        }
    }
    return isValid;
}

Can anyone please help on this.

Upvotes: 0

Views: 1489

Answers (4)

Joakim Danielson
Joakim Danielson

Reputation: 51920

Since it would be possible for an url to have a domain name anywhere (abc.computer.xxx.com) I think you should use endsWith. Here is a solution using streams

 boolean isOk = arrayList.stream().anyMatch( dom -> reqUrl.endsWith(dom.toLowerCase()));

Upvotes: 0

burm87
burm87

Reputation: 848

You may be able to use Streams api:

public static boolean isListContainValidDomain(List<String> arraylist) {
    final String reqURL = "dev.def.com";
    boolean isValid = arraylist.stream().anyMatch(domain -> reqURL.contains(domain));
    return isValid;
}

Upvotes: 1

stevecross
stevecross

Reputation: 5684

You should invert the condition. As it is now your function will only return true if your string contains all strings in the list.

public static boolean isListContainValidDomain(List<String> arraylist) {
    String reqURL = "dev.def.com";

    for (String str : arraylist) {
        if (reqURL.contains(str.toLowerCase())) {
            return true;
        }
    }

    return false;
}

Upvotes: 2

vavasthi
vavasthi

Reputation: 952

Why don't you construct a regex that incorporates all the domains. Basically your ArrayList = [abc.com, def.com, xyz.com] should be converted to a string that looks like (abc.com | def.com | xyz.com) then you can just do a single regex match.

Upvotes: 1

Related Questions