Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 8 change list to map using instance of list

I'm try to convert a list to a map using the Collectors.toMap call. The list consists of ActivityReconcile objects. I want to pass an instance for every entry in the list into the toMap call.

The code is below and where I need the instances is denoted by ??.

final List<ActivityReconcile> activePostedList = loader.loadActivePosted(accessToken);
Map<AccountTransactionKey, ActivityReconcile> postedActiveMap = 
activePostedList.stream().collect(
 Collectors.toMap(
 AccountTransactionKey.createNewAccountTransactionKeyFromActivityReconcileRecord(??),??));
like image 564
richs Avatar asked Mar 30 '16 17:03

richs


2 Answers

If I understood you correctly, you will need something like

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

And the method (in AccountTransactionKey class) will look like

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

I've replaced createNewAccountTransactionKeyFromActivityReconcileRec by generate for making the answer more readable and understandable.

like image 121
Andrew Tobilko Avatar answered Oct 22 '22 04:10

Andrew Tobilko


To "fix" your code with the least changes, add a lambda parameter:

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

or use a method reference:

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

btw, I can't recall ever seeing a method name as long as createNewAccountTransactionKeyFromActivityReconcileRecord - for readability, consider reducing it to just create(), since the return type and parameter type are enough to distinguish it from other factory methods you may have.

like image 32
Bohemian Avatar answered Oct 22 '22 04:10

Bohemian