Peter
Peter

Reputation: 39

Very minor code optimisation

  while (i < a.size() && value2.substring(0, prefix.length()).compareTo(prefix) == 0) {
        value2 = a.get(i);

        if (value2.endsWith(suffix)) {
            counter++;
            setter = true;

        }

        i++;

    }

I was just wondering if there was a way to avoid using the get() method twice in my code. My problem right now is that I need to assign value 2 before so that my while loop works but I also need to update it within the while loop.

Upvotes: 0

Views: 60

Answers (4)

liangwei
liangwei

Reputation: 11

in java8, you can use stream like this:

    counter = a.stream()
           .filter(s -> s.startsWith(prefix))
           .filter(s -> s.endsWith(suffix))
           .count();
    setter = counter > 0;

Upvotes: 1

Ke Li
Ke Li

Reputation: 952

Maybe this is what you need:

for (String value : a) {
        if (!value.startWith(prefix)) break;
        if (value.endsWith(suffix)) {
            counter++;
            setter = true;
        }
    }

If a is not iterable:

        while(i < a.size()){
        String value = a.get(i);
        if (!value.startsWith(prefix))
            break;
        if(value.endsWith(suffix)){
            counter++;
            setter = true;
        }
        i++;
    }

Upvotes: 4

Ken Y-N
Ken Y-N

Reputation: 15009

This is similar to a Python issue about not being able to assign in conditions; we can use the while(true) if () break; idiom instead - actually, we cannot do while (true) as we'll crash on i == a.size(), so instead we'll split the code into a while and an if:

while (i < a.size())
{
    String value2 = a.get(i);
    if (value2.substring(0, prefix.length()).compareTo(prefix)==0)
    {
        if(value2.endsWith(suffix)){
            counter++;
            setter = true;
        }
    }
    else
    {
        break;
    }
    i++;
}

(Oh, and please try to format your code with regular indentation levels; it makes things so much easier to follow for not just us, but you too.)


Following on from comments below, one can also do the shorter, but in my opinion harder to read:

String value2;
while (i < a.size() && (value2 = a.get(i)).substring(0, prefix.length()).compareTo(prefix)==0)
{
    if(value2.endsWith(suffix))
    {
        counter++;
        setter = true;
    }
    i++;
}

In this case, with the assignment in the middle of the second expression, I think it is easy for the reader to overlook.

Upvotes: 1

happy programmer
happy programmer

Reputation: 110

        while(i <a.size()){
            value2 = a.get(i);
            if(value2.substring(0,prefix.length()).compareTo(prefix)!=0){
                break;
            }
            if(value2.endsWith(suffix)){
                counter++;
                setter = true;

            }
            i++;
       }

Upvotes: 1

Related Questions