Pavol
Pavol

Reputation: 572

Map two ArrayList with lambdaj?

I have two classes

public class User {
    private int _Id;
    private String _FirstName;
    private String _LastName;}

and

public class Card {
    private int _Id;
    private int _UserId;
    private String _Serial;}

I have Array of User[] and Card[]. And i want to create HashMap<String, User> where User._Id == Card._UserId and string (in HashMap) is _Serial from Cards... I think i can use lambdaj but i don't know how..

Upvotes: 1

Views: 126

Answers (1)

martinhh
martinhh

Reputation: 346

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));

}

}

Upvotes: 0

Related Questions