5
I have a list of columns, I need to know if this list contains both columns that are keys and columns that are not keys.
I guarantee the existence of at least one column on the list
My class of column:
public class Coluna {
public boolean chave;
public boolean isChave() { return chave; }
}
My check is like this at the moment:
List<Coluna> minhasColunas = ...;
Predicate<Coluna> ehChave = Coluna::isChave;
boolean possuiColunasMistas =
minhasColunas.stream().anyMatch(ehChave) &&
minhasColunas.stream().anyMatch(ehChave.negate());
Is there any more idiomatic way to do this check? I found it very strange to go through two streams to obtain the result.
On a more imperative check, I would do the following:
List<Coluna> minhasColunas = ...;
boolean achouChave = false;
boolean achouNaoChave = false;
for (Coluna c: minhasColunas) {
if (c.chave) {
achouChave = true;
if (achouNaoChave) {
break;
}
} else {
achouNaoChave = true;
if (achouChave) {
break;
}
}
}
boolean possuiColunasMistas = achouChave && achouNaoChave;
After the creation of the question, and conversation with the @Anderson Carlos Woss, I ended up creating some test scenarios for that question. They are available here: https://gitlab.com/snippets/1724680
So if you want to validate your own response, implement the method boolean possuiColunasMistas(List<Coluna> colunas)
and then just run with Junit the test cases.
It is necessary to use stream or a reply iterating a for is valid ?
– Vinícius Ferreira
@Viníciusferreira my ultimate goal is elegance. In this question, it was really how to use
stream
, I sensed I had something wrong. So, elegant answers are appreciated, even though the focus is not– Jefferson Quesado