Menu

How to map collection?

Help
hez
2009-02-17
2013-05-02
  • hez

    hez - 2009-02-17

    Hi

    I have a class User, and another class UserDto.

    Here is how I map a list of User to a list of UserDto:

    List<User> users = ...
    List<UserDto> temp = new ArrayList<UserDto>(users.size());
    for (User user : users) {
        UserDto dto= (UserDto) mapper.map(user, UserDto.class);
        temp.add(dto);
    }

    Is there a more elegant way of mapping a collection to another collection without the loop?

    /newbie

     
    • Matt Tierney

      Matt Tierney - 2009-02-18

      Nested collections are handled automatically, but you are correct that top level collections need to be iterated over.  Currently there isn't a more elegant way to handle this.

      Thanks,
      Matt

       
    • YohannB

      YohannB - 2009-05-11

      Hi,

      after trying some combinations, I succeded to make dozer map two collection of different element types.
      I don't think it is very elegant, since as far as I know, you must duplicate this XML fragment for any new couple of types :

          <mapping map-id="collectionMapping" type="one-way">
              <class-a>java.util.Collection</class-a>
              <class-b>java.util.Collection</class-b>
              <field>
                  <a>this</a>
                  <b set-method="add(java.lang.Object)" type="iterate">anything</b>
                  <b-hint>your destination object type</b-hint> 
              </field>
          </mapping>

      A way to make the previous XML fragment a bit more generic would be to make the b-hint tag optional. We can suppose that the dst collection has been filled with target beans. So that the mapping could be decided at runtime thanks to the element types of src and dst collections according to existing mappings.

      The Collection framework is one of the main fundation of Java. In my opinion, Dozer should supply a convenient API to handle collections at top level.
      It would be much more easy if we could use something like :
      <S, D> Collection<D> map(Collection<S> srcCollection, Class<D> targetClass);
      or à la spring jdbc :
      <S, D> Collection<D> map(Collection<S> srcCollection, ParameterizedObjectMapper<S, D> mapper);

      Thanks,
      Yohann.

       
    • Muris Ahmovic

      Muris Ahmovic - 2009-09-09

      Hi,

      has there already been a progress in this direction?

      Regards,
      GND

       
    • Stefan Bley

      Stefan Bley - 2009-09-11

      Instead of looping through the collection I prefer putting them in a wrapper object and using nested collection wrapping.

       
  • Pramod

    Pramod - 2012-07-26

    @Yohann: Could you please post the exact dozer mapping required to convert

    List<UserDto>
    

    to

    List<User>
    

    .

    Sorry, I haven't understood your post.

     

Log in to post a comment.

MongoDB Logo MongoDB