List of java 8 changes to match using list instance

I am trying to convert a list to a map using a call to Collectors.toMap . The list consists of ActivityReconcile objects. I want to pass an instance for each entry in the list to a toMap call.

The code below and where I need the instances is indicated by the symbol.

 final List<ActivityReconcile> activePostedList = loader.loadActivePosted(accessToken); Map<AccountTransactionKey, ActivityReconcile> postedActiveMap = activePostedList.stream().collect( Collectors.toMap( AccountTransactionKey.createNewAccountTransactionKeyFromActivityReconcileRecord(??),??)); 
+7
java java-8 java-stream
source share
2 answers

If I understood you correctly, you would need something like

 Map<AccountTransactionKey, ActivityReconcile> result = choices .stream() .collect(Collectors.toMap( AccountTransactionKey::generate, Function.identity())); 

And the method (in the AccountTransactionKey class) will look like

 public static AccountTransactionKey generate(ActivityReconcile reconcile) {...} 

I replaced createNewAccountTransactionKeyFromActivityReconcileRec with generate to make the answer more understandable and understandable.

+4
source share

To β€œfix” your code with the least changes, add the lambda parameter:

 activePostedList.stream().collect(Collectors.toMap( ar -> AccountTransactionKey.createNewAccountTransactionKeyFromActivityReconcileRecord(ar)), o -> o)); 

or use the link to the method:

 activePostedList.stream().collect(Collectors.toMap( AccountTransactionKey::createNewAccountTransactionKeyFromActivityReconcileRecord, o -> o)); 

btw, I can’t ever remember the look of the method name until createNewAccountTransactionKeyFromActivityReconcileRecord - for readability, consider reducing it to just create() , since the return type and parameter type are enough to distinguish it from another factory methods you may have.

+3
source share

All Articles