whoismaikl
whoismaikl

Reputation: 314

How can I convert this for loop to java 8 stream analog

How can I convert this code to java 8 stream.

Tried to use for each, but failed. For loop code is working.

for(RestrictedInstrument restrictedInstrument : restrictedInstruments){
    List<Identifier> identifierList = restrictedInstrument.getIdentifier();
    setTicker(matrix, identifierList);
}

setTicker() method should be called with matrix Object and identifierList.

Upvotes: 0

Views: 168

Answers (3)

Avik Kesari
Avik Kesari

Reputation: 289

You can stream the list and then simply pass consumer which just calls setTicker function.

 restrictedInstruments.stream()
.forEach(identifierList -> setTicker(matrix, identifierList.getIdentifier()));

Upvotes: 1

Samuel Philipp
Samuel Philipp

Reputation: 11050

You can just use List.forEach():

restrictedInstruments.forEach(i -> setTicker(matrix, i.getIdentifier()));

Upvotes: 2

n1t4chi
n1t4chi

Reputation: 492

Assuming restrictedInstruments is list, first you map to identifierList, then you use Stream.forEach() to execute setTicker(...) method

restrictedInstruments
  .stream()
  .map( RestrictedInstrument::getIdentifier )
  .forEach( identifierList -> setTicker(matrix, identifierList) )

For arrays just use Arrays.stream( restrictedInstruments )

Upvotes: 1

Related Questions