Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How shorten if statements using lambda expressions?

Tags:

java

lambda

First of all, I'm aware that there is a similar questions like this. The answer to that question, however, did not help me.

I have the following code:

boolean result = fields[x][y + 1].getRing().getPlayer() == player || fields[x][y - 1].getRing().getPlayer() == player || fields[x + 1][y].getRing().getPlayer() == player || fields[x - 1][y].getRing().getPlayer() == player

The code is supposed to check if there are any rings of the current player above, under or next to the current field.

I'm trying to make this code more readable by using a lambda expression, but I can't get it right. I'm not sure whether this is even possible, though.

I tried to replace fields[x][y] by a variable field and then have field become fields[x][y+1], fields[x][y-1], fields[x+1][y], fields[x-1][y]

boolean result = field.getRing().getPlayer() == player -> field = {fields[x][y+1], fields[x][y-1], fields[x+1][y], fields[x-1][y]};

But this gives me a syntax error, which I expected, since field = {fields[x][y+1], fields[x][y-1], fields[x+1][y], fields[x-1][y]}; sets field to an array, and does not iterate over that array.

Is there any way I can make this code shorter using lambda expression?

like image 972
HYBR1D Avatar asked Jun 24 '26 12:06

HYBR1D


1 Answers

You keep repeating the same condition, on 4 different values. So what you want in fact is to avoid this repetition, and write the condition once. And you want to test if any of the 4 values match the condition. So start by storing the 4 values in a collection:

List<Field> neighbors = Arrays.asList(fields[x + 1][y],
                                      fields[x - 1][y],
                                      fields[x][y + 1],
                                      fields[x][y - 1]);

Then test if any of those values match the condition:

boolean result = neighbors.stream().anyMatch(field -> field.getRing().getPlayer() == player);

This doesn't necessarily make the code faster or shorter, but it makes it more readable, and DRY.

like image 124
JB Nizet Avatar answered Jun 26 '26 02:06

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!