Hey :slightly_smiling_face: can I `map` a `SortedS...
# announcements
s
Hey 🙂 can I
map
a
SortedSet
without transitioning the whole thing to a
List
?
d
collection.mapTo(targetCollection) { ... }
👍 2
So e.g.
collection.mapTo(TreeSet()) { ... }
s
ah thanks. I’ll check that out
d
Normal
map
would preserve it, too (by adding to a list). When using
mapTo
the resulting order depends on the collection you are mapping to. If you are mapping to a
HashSet
for example you won't get any ordering guarantees.
If you use
LinkedHashSet
you will get same order as source.
If you use
TreeSet
you will get order based on comparing entries
s
The definition of the map-to is:
Applies the given transform function to each element of the original collection and appends the results to the given destination.
so I would assume a treeset would preserve the comparator I provided…
why do you think the linkedHashSet will get the same order ? Can you explain this ?
d
Because LinkedHashSet preserves iteration order.
mapTo
will iterate through your source collection and add the mapped element to the LinkedHashSet
So the resulting set will have the same order as your source collection
s
ok thanks
d
It acts like a for loop, basically
Reading from source and appending to the target collection
s
yeah that’s what is sais. Make sense
a
The "appending" might be a bad word choice though, it's "adding" to the destination collection, which might be appending depending on the collection