Gathering the elements of a stream into a set, is there any advantage (or disadvantage) that also defines .distinct()the stream? For instance:
.distinct()
return items.stream().map(...).distinct().collect(toSet());
Given that the kit will already remove duplicates, this seems redundant, but does it offer any performance advantages or disadvantages? The answer depends on whether the stream is parallel / sequential or ordered / disordered?
According to javadoc , it distinctis an intermediate state operation.
distinct
.distinct, .collect, . , .distinct , Set, , , .
.distinct
.collect
Set
, , .distinct .map, , , .
.map
, : toSet() HashSet, , :
toSet()
HashSet
javadoc:
() (, , ), . (, ()) BaseStream.unordered() () , . , () , BaseStream.sequential() .
, distinct(). toSet() ( API).
distinct()
, equals, :
equals
class F { int a; int b; @Override int hashCode() {return Objects.hashCode(a);} @Override boolean equals(Object other) { if (other == this) return true; if (!(other instanceof F)) return false; return a == ((F)other).a; } }
a = F(10, 1) b = F(10, 2), . .
a = F(10, 1)
b = F(10, 2)
(b, a)
, , ( ..).
. TreeSet compareTo.
TreeSet
compareTo
different will call equals / hashcode to separate the elements, and later toSet will do the same (even if after parsing is not necessary, but toSet cannot really know this), so basically you just duplicate the calls. This should be worse than IMO. It is also quite easy to measure.
Source: https://habr.com/ru/post/1666511/More articles:How to get tweets older than a few months? - c #Retrieving results from a search object to search on twitter - c #Spark Streaming с Hbase - hbaseHow to populate a column of a result view with a value from stored code in SQL? - sqlTomcat 8 org.apache.commons.io.FilenameUtil - javaLooking for the smallest missing integer in a vector containing positive and negative int? - c ++PhpStorm and Jira Integration - phpstormИзвлечь все подстроки, начинающиеся и заканчивающиеся регулярным выражением из большой строки - javaUnable to access UserInfo endpoint in sample IdentityServer4 document from client - asp.net-coreSafari and iphone block redirection from iframe - safariAll Articles