Reputation: 878
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
...
what is the time complexity of below operation? O(n) or O(1)?
set.stream().filter(e -> e == 1).findFirst();
Upvotes: 2
Views: 799
Reputation: 13783
It's O(n) - after you create a Stream
instance, you are no longer operating on a HashSet
, but on a Stream
that goes over all elements of the source Set
.
It's a lazy linear sequence where all elements are visited one by one - hence O(n)
Upvotes: 1
Reputation: 59960
You can understand it better if you see it from another side, your solution is same like this :
for(Integer i : set){
if(i == 1){
break;
}
}
So it is O(n)
because it loop over all the set, and check one by one, if the condition is correct return the value else continue until n
elsement
Upvotes: 1