I am writing some examples of Java programs on GitHub rsp/ppj for people to learn and I want them to be as simple and compact as possible, to work on Java 1.7.x (a.k.a. Java 7) and to not use any non-standard libraries that need installation.
This question is about my WhereEven example:
a function of an int[]
array that returns an int[]
array with only even numbers
(The method can internally use any other data types if it makes sense.)
Here is how my example looks like right now:
static int[] even(int[] t) {
int i, j;
for (i=j=0; i < t.length; i++)
if (t[i] % 2 == 0) j++;
int[] r = new int[j];
for (i=j=0; i < t.length; i++)
if (t[i] % 2 == 0) r[j++] = t[i];
return r;
}
I am not satisfied with that code because it is much more complex than the same in JavaScript - even using the old ES5 syntax (few years older than Java 7) it is:
function even(t) {
return t.filter(function(x){ return x % 2 == 0; });
}
It is even better in Scheme, which is amazing considering the fact that this is a language that's 40 years old:
(define (even t)
(filter even? t))
But I can't get to the solution that is even remotely as simple and readable in Java. Of course I can add comments and more meaningful variable names, but the point is that in Scheme and JS the code is simple and the meaning is obvious as it is. What I am looking for is a way to write a better code, not to write the same code but with better names.
What in your opinion is "the best" way to improve the above code to be most useful for an educational example like this? Maybe the shortest way in terms of lines/characters, the most readable way, the most idiomatic way, the way using best practices, the most crazy way? I am looking forward to every suggestion of my code improvement that would help people learn something about Java and maybe I'll put few different approaches in my tutorial.
The only requirement is taking an int[]
array, returning a new int[]
array (but internally the method can use any other data types if it makes sense), working on Java 1.7.x (a.k.a. Java 7) and not using any non-standard classes.
int[]
array may not be the idiomatic data structure to use in the first place. \$\endgroup\$IntStream.of(t).filter(i -> (i & 1) == 0).toArray()
<- done. \$\endgroup\$