Enosh Bansode
Enosh Bansode

Reputation: 1778

Filtering List without using iterator

I need to filter a List of size 1000 or more and get a sublist out of it. I dont want to use an iterator.

1) At present I am iterating the List and comparing it using Java. This is time consuming task. I need to increase the performance of my code.

2) I also tried to use Google Collections(Guava), but I think it will also iterate in background.

  Predicate<String> validList = new Predicate<String>(){  
      public boolean apply(String aid){  
          return aid.contains("1_15_12");  
      }  
  }; 
   Collection<String> finalList =com.google.common.collect.Collections2.filter(Collection,validList);

Can anyone suggest me how can I get sublist faster without iterating or if iterator is used I will get result comparatively faster.

Upvotes: 2

Views: 575

Answers (4)

Gabriel Ščerb&#225;k
Gabriel Ščerb&#225;k

Reputation: 18570

If the performance is really your concern, most probably the predicate is pretty slow. What you can do is to Lists.partition your list, filter in parallel (you have to write this) and then concatenate the results.

There might be better ways to solve your problem, but we would need more information about the predicate and the data in the List.

Upvotes: 0

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

I enrich my comment: I think iterator is inevitable during filtering, as each element has to be checked.

Regarding to Collections2.filter, it's different from simple filter: the returned Collection is still "Predicated". That means IllegalArgumentException will be thrown if unsatisfied element is added to the Collection.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500485

Consider what happens if you call size() on your sublist. That has to check every element, as every element may change the result.

If you have a very specialized way of using your list which means you don't touch every element in it, don't use random access, etc, perhaps you don't want the List interface at all. If you could tell us more about what you're doing, that would really help.

Upvotes: 1

never
never

Reputation: 681

List is an ordered collection of objects. So You must to iterate it in order to filter.

Upvotes: 0

Related Questions