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
Post a Comment