In my Java application I'm using the following stream:
columns.stream()
.map(columnEncryptors::get)
.findFirst()
.ifPresentOrElse(columnEncryptor ->
columnEncryptor.encrypt(bankTransaction),
() -> { throw new IllegalArgumentException("No encryptor"); }
);
The columns
list met contains 9
strings, the code above is performing the action only for the first one, but not the other 8
.
How can change the code fire the same action for every element in the columns
list?
CodePudding user response:
To apply the action on every element you don't need findFirst
, deal with Optional
and there's no need to create a stream at all.
columns.forEach(column -> {
ColumnEncryptor encryptor = columnEncryptors.get(column);
if (encryptor != null) columnEncryptor.encrypt(bankTransaction)
else throw new IllegalArgumentException("No encryptor");
});
CodePudding user response:
The reason you are only able to process first one is because of the .findFirst
. You can try using .forEach
instead then all the elements in the stream will be processed:
columns.stream()
.map(columnEncryptors::get)
.forEach((columnEncryptor) -> {
<LOGIC FOR EACH ELEMENT>
})