If i have a list (~200 elements) of objects, with only few unique objects (~20 elements).
I want to have only unique values. Between list.stream().collect(Collectors.toSet()) and list.stream().distinct().collect(Collectors.toList())
which is more efficient wrt latency and memory consumption ?
答案 0 :(得分:4)
A Set
(typically HashSet
) consumes more than a List
(typically ArrayList
), mainly because of the hashing table that it stores. But with so few elements, you will not get a noticeable difference in terms of memory consumption.
Instead, which you should care about is that these collectors return different things : a List
and a Set
that have their own specificities, particularly as as you access to their elements.
So use the way that matches to what you want to perform with this collection.