简体   繁体   中英

Time complexity of this code using Java 8 stream and predicate

I have a map from which I am trying to retrieve data using Java 8 stream and a filter down using a predicate.

But I have huge doubts about the complexity of the code. Can anyone help me figuring out the time complexity of this code.

class Student{
   String id;
}
Multimap<Integer, String> map = HashMultimap.create();
    map.put(1, new Student("id1"));
    map.put(2, new Student("id1"));
    map.put(1, new Student("id2"));
    map.put(1, new Student("id3"));

// Time complexity of this ???
map.get(1).stream().filter(p -> p.getId().equals("id1"))
                    .collect(Collectors.toSet());

The simple answer for your stream code is O(1), because you have not specified a terminal operation and streams are lazy evaluated. So at the moment your stream code does no stream processing at all.

The map.get(1) operation returns an already calculated Set. So the complexity is the one to find that entry: O(1), like one of the commentators already said.

After your edit it should be O (n).

But as Brian said think about correct code and not complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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