简体   繁体   English

使用lambdaj映射两个ArrayList?

[英]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[] . 我有User[]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.. 我想创建HashMap<String, User> ,其中User._Id == Card._UserId和字符串(在HashMap中)是来自卡片的_Serial ...我想我可以使用lambdaj但我不知道如何...

Unfortunately I don't know lambdaj, so I can not offer a solution using lambdaj. 不幸的是我不知道lambdaj,所以我无法使用lambdaj提供解决方案。 But I think one can solve the problem reasonably elegant and effectively with plain Java in two steps. 但我认为可以通过两个步骤使用普通Java来合理地优雅和有效地解决问题。

  • The first step maps User._Id to User 第一步将User._Id映射到User
  • The second step uses the first Map to map Card._Serial to User 第二步使用第一个Map将Card._Serial映射到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. 因为我不喜欢Arrays,所以我使用了用户和卡片列表作为输入。

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

}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM