Time complexity of stream filter

zonyang :

I have a code like this:

List<Listing> Listings = new ArrayList<>();
Listings.add(listing1);
Listings.add(listing2);
...
...
...

Listing listing= listings.stream()
                .filter(l -> l.getVin() == 456)
                .findFirst();

My question is what is the time complexity of the filter process? If it is O(n), my intuition is to convert it into HashSet like data structures so that the time complexity could become O(1), Is there an elegant way to do this with streams?

Adam :

It is O(n). The stream filtering uses iteration internally.

You could convert it to a map as follows:

Map<Integer, Listing > mapOfVinToListing = listings.stream().collect(Collectors.toMap(Listing::getVin, Functions.identity()); // Assuming vin is unique per listing
mapOfVinToListing.get(456);// O(1)

But, that conversion process is also O(n). So, if you only need to do this once, use the filter. If you need to query the same list many times, then converting it to a map may make sense.

You might also try using parallel streams. In some cases they may be more performant, but that depends a lot on the exact circumstances.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=437489&siteId=1