Is order preserved when mapping lists?

268 views
Skip to first unread message

Christoph Lucas

unread,
Jan 28, 2021, 4:51:32 AM1/28/21
to modelmapper
Hello

We have been using ModelMapper for quite a while, and now we want to start mapping lists as well. I found a good documentation on how to do this here:


Yet, I couldn't find a statement / guarantee that the order of the list is preserved during the mapping process. So my question is: Is the order preserved when mapping lists in the way described in the example above?

Any help would be highly appreciated!

Best regards,
Christoph

Nathan

unread,
Jan 31, 2021, 4:56:05 PM1/31/21
to modelmapper
Hi Christoph,

It's been a while since I've used ModelMapper but I'm pretty confident that order is preserved. I had a quick look into the code on github and I think (I could be wrong) it's either using the MergingCollectionConverter or NonMergingCollectionConverter here https://github.com/modelmapper/modelmapper/tree/master/core/src/main/java/org/modelmapper/internal/converter

Both are just using the iterator from the source Iterable, which would mean that if you are using a source and destination Iterables that preserve order (ArrayList etc), then model mapper will preserve order.

In the past I've also used little utility functions to avoid having to mess around with TypeTokens etc, something like

    public <T> List<T> map(Iterable<?> source, Class<T> destination) {
        return stream(source.spliterator(), false)
                .map((elem) -> this.mapper.map(elem, destination))
                .collect(Collectors.toList());
    }

Cheers,
Nathan

Christoph Lucas

unread,
Feb 1, 2021, 11:55:44 AM2/1/21
to modelmapper
Hi Nathan,

Thank you very much for your reply and the dive into the source code. I guess for now I would use your little utility function, just to be safe. However, it would be great if they could put that guarantee on the "interface" so that one can rely on it even in future versions of the library.

Best regards,
Christoph
Reply all
Reply to author
Forward
0 new messages