Is there a way to dynamically change conditions in if statement in Java?
<p>I have this code that filters a String <code>str</code>, keeping only some <code>chars</code>, resulting in the reduced String <code>fStr</code>. The subtlety is that I only keep a target <code>char</code>, if it is not equal to the last <code>char</code> in <code>fStr</code>:  </p>

<pre><code>ArrayList&lt;Character&gt; targetChars = //{a, b, c};
String str = "axxbxxxxbxbxcxa", fStr = "";

for(int i = 0, s = 0 ; i &lt; str.length() ; i++) {
    char c = str.charAt(i);
    if(targetChars.contains(c)) {
        if(s &gt; 0 &amp;&amp; fStr.charAt(s-1) != c) {
            fStr += c;
            s++;
        }
    }
}  
</code></pre>

<blockquote>
  <p>fStr → "abca"</p>
</blockquote>

<p>In the innermost <code>if</code> statement, I have to include <code>s &gt; 0</code> before <code>fStr.charAt(s-1) != c</code>, otherwise the latter will throw an <code>OutOfBounds</code> exception the first time <code>targetChars.contains(c)</code> is <code>true</code>. But <em>only</em> the first time, it annoys me that the loop will always check that I won't be out of bounds, given that it only has to do it once. I know I could do something like that:  </p>

<pre><code>ArrayList&lt;Character&gt; targetChars = //{a, b, c};
String str = "auebskrubnbocpa", fStr = "";
int i = 0, s = 0;   

for(; i &lt; str.length() ; i++) {
    char c = str.charAt(i);
    if(targetChars.contains(c)) {
            fStr += c;
            s++;
            i++;
            break;
    }
}

for(; i &lt; str.length() ; i++) {
    char c = str.charAt(i);
    if(targetChars.contains(c)) {
        if(fStr.charAt(s-1) != c) {
            fStr += c;
            s++;
        }
    }
}
</code></pre>

<p>But is there a more elegant and less annoying way to dynamically truncate a conditional statement?</p>