Time complexity of stream filter

前端 未结 3 1199
情话喂你
情话喂你 2021-02-08 00:35

I have a code like this:

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

Listing listing= li         


        
3条回答
  •  花落未央
    2021-02-08 00:54

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

    You could convert it to a map as follows:

    Map 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.

提交回复
热议问题