Java 8 lambdas grouping reducing and mapping -


given list of following transaction class, using java 8 lambdas, want obtain list of resultantdto, 1 per account type.

public class transaction {      private final bigdecimal amount;     private final string accounttype;     private final string accountnumber;  }  public class resultantdto {      private final list<transaction> transactionsforaccount;      public resultantdto(list<transaction> transactionsforaccount){         this.transactionsforaccount = transactionsforaccount;     }  } 

so far, use following code group list<transaction> accounttype.

map<string, list<transaction>> transactionsgroupedbyaccounttype = transactions     .stream()     .collect(groupingby(transaction::getaccounttype)); 

how return list<resultantdto>, passing list each map key constructor, containing 1 resultantdto per accounttype?

you can in single stream operation:

public list<resultantdto> convert(list<transaction> transactions) {     return transactions.stream().collect(             collectingandthen(                 groupingby(                         transaction::getaccounttype,                         collectingandthen(tolist(), resultantdto::new)),                 map -> new arraylist<>(map.values()))); } 

here collectingandthen used twice: once downstream collector convert lists resultantdto objects , once convert resulting map list of values.


Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -