1

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..

Pavol
  • 552
  • 8
  • 19
  • Zip the two lists together, then map over the zipped list. I'm 90% site Java has the ability to zip lists. – Carcigenicate Jul 07 '16 at 12:55
  • Possible duplicate of [How to Iterate through two ArrayLists Simultaneously?](http://stackoverflow.com/questions/15985266/how-to-iterate-through-two-arraylists-simultaneously) – Carcigenicate Jul 07 '16 at 12:56

1 Answers1

0

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

}

}

martinhh
  • 336
  • 2
  • 10
  • Actually, I didn't see the android tag when I posted this answer :-S I am not sure if this works for android... But I am sure, someone will tell me soon! – martinhh Jul 07 '16 at 16:37