简体   繁体   English

从HashSet获得的流过滤器的时间复杂度是多少?

[英]What is the time complexity of stream filter obtained from HashSet?

Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
...

what is the time complexity of below operation? 以下操作的时间复杂度是多少? O(n) or O(1)? O(n)或O(1)?

set.stream().filter(e -> e == 1).findFirst();

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 因此它是O(n)因为它遍历所有集合,并一个接一个地检查,如果条件正确,则返回值,否则继续执行,直到n

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 . 它是O(n)- 创建Stream实例后,您将不再对HashSet ,而是对遍历源Set所有元素的Stream进行操作。

It's a lazy linear sequence where all elements are visited one by one - hence O(n) 这是一个惰性线性序列,其中所有元素都被一个一个地访问-因此O(n)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM