Unfortunately I don't know lambdaj, so I can not offer a solution using lambdaj.
But I think one can solve the problem reasonably elegant and effectively with plain Java in two steps.
- The first step maps User._Id to User
- The second step uses the first Map to map Card._Serial to User
I didn't test the code but I am very optimistic that it works ;-)
As I don't like Arrays, I used Lists of Users and Cards as input.
Hope this helps!
public class CardToUserMapper {
public Map<String, User> mapCardsToUser(
final List<User> users,
final List<Card> cards) {
Map<Integer, User> idToUser =
users.stream()
.collect(Collectors.toMap(
u -> u.getId(),
u -> u));
Map<String, User> serialToUser =
cards.stream()
.collect(Collectors.toMap(
c -> c.getSerial(),
c -> idToUser.get(c.getUserId())));
return serialToUser;
}
}
If one like it more condensed, one can do it like this:
public class CardToUserMapper {
public Map<String, User> mapCardsToUser(final List<User> users,
final List<Card> cards) {
return mapSerialToUser(cards, mapUserIdToUser(users));
}
private Map<String, User> mapSerialToUser(final List<Card> cards,
final Map<Integer, User> idToUser) {
return map(cards, c -> c.getSerial(), c -> idToUser.get(c.getUserId()));
}
private Map<Integer, User> mapUserIdToUser(final List<User> users) {
return map(users, u -> u.getId(), u -> u);
}
private <S, T, U> Map<T, U> map(final List<S> listOfS, final Function<S, T> funcStoT,
final Function<S, U> funcStoU) {
return listOfS.stream().collect(Collectors.toMap(funcStoT, funcStoU));
}
}