Shiv
Shiv

Reputation: 851

Optimising multiple Java array additions

I have the following code

JsonObject domainsObject = new JsonParser().parse(json).getAsJsonObject().get("data").getAsJsonObject();
        this.domain = domainsObject.get("main_domain").getAsString();

        this.domains.add(this.domain);

        for(JsonElement domain : domainsObject.get("addon_domains").getAsJsonArray()) {
            this.domains.add(domain.getAsString());
        }

        for(JsonElement domain : domainsObject.get("parked_domains").getAsJsonArray()) {
            this.domains.add(domain.getAsString());
        }

        for(JsonElement domain : domainsObject.get("sub_domains").getAsJsonArray()) {
            this.domains.add(domain.getAsString());
        }

However I want to optimise it properly because it seems like there will be a way to do this without needing to oppose DRY.

Is there a way to squash the 3 separate arrays and the lone string all into one array without looping through each one manually?

Upvotes: 2

Views: 81

Answers (2)

Anonymous
Anonymous

Reputation: 86389

I see basically two ways, each with its advantages and limitations.

Grzegorz Górkiewicz menitoned one already, a list and a loop. Instead of a list I’d use an array:

String[] parameters = { "addon_domains", "parked_domains", "sub_domains" };

for(String parameter : parameters) {
    for(JsonElement domain : domainsObject.get(parameter).getAsJsonArray()) {
        this.domains.add(domain.getAsString());
    }
}

If you like the list better, use Arrays.asList("addon_domains", "parked_domains", "sub_domains"). As Chai T. Rex mentions in the comment, you may declare the array or list private static final outside the method to avoid building it again each time you use it.

The other is to call an auxiliary method:

addDomainsFromParameter("addon_domains");
addDomainsFromParameter("parked_domains");
addDomainsFromParameter("sub_domains");

(You know your program better and can find a better method name. I trust you to write the method yourself.) The advantage of the latter comes if at some point you need variations on the processing, then you can add more parameters to the method.

Upvotes: 3

Grzegorz Górkiewicz
Grzegorz Górkiewicz

Reputation: 4596

Place them in a list.

List<String> parameters = new ArrayList<>();
parameters.add("addon_domains");
parameters.add("parked_domains");
parameters.add("sub_domains");

for(String parameter : parameters) {
    for(JsonElement domain : domainsObject.get(parameter).getAsJsonArray()) {
        this.domains.add(domain.getAsString());
    }
}

Upvotes: 3

Related Questions