0

I want to use the fastest possible method to match a String with a String in List.

Im iterating trough a list to match productname and set price for that product.

Im trying to match every 400 000 items by name in another list where i could find the price, that list also contains 400 000 items.

Doing a "contains()" on String to match 400 000 items 400 000 times takes a long time to finish. I did also try startsWith() as i dont search by substring, im using the String because there is for sure a full match in the second list. It just has to be a faster way to find a match in the inner for loop to get the price?

ProductData t = null;
for (int i = 0; i < ParseCSV.products.size(); i++) {  // List of 400K+ items
        t = ParseCSV.products.get(i);

        for (int j = 0; j < ParseCSVprice.productPrice.size(); j++) {  // another List of 400K+ items
        if (ParseCSVprice.productPrice.get(i).getpairID()
                .contains(t.pairID)) {

            t.price = ParseCSVprice.productPrice.get(i).getPrice();
        }

    }
rainbowpol
  • 11
  • 2

2 Answers2

0

You need to use another structure probably.
Possibly a HashMap or a HashSet.
There's no much faster way by using a List.
Searching in a List is O(N).

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
0

If you only expect one or zero matches, you can increase the speed of your code in some cases by stopping your loops using the break keyword after you have found the match.

Also you might consider changing your id fields to contain numeric values which would be faster to compare than strings.

Because you are having to call a method on each object in the List in order to make the comparison, there isn't much else you can do to speed this up

Jamie Holdstock
  • 166
  • 1
  • 11
  • I absolutely should break; how could i miss that! :) That could in best case make it finish a lot faster. Half the time maybe. I will try this. I can´t change the fields, i get those values from other systems. – rainbowpol Mar 04 '14 at 21:48
  • The break keyword in this case made it finish in 49% of the time it took before :) – rainbowpol Mar 04 '14 at 21:52
  • See [this answer](http://stackoverflow.com/a/886979/1428338) for a great example of how to break out of both loops with only one break statement from inside your if statement. If you weren't doing that before it may be even faster – Jamie Holdstock Mar 04 '14 at 21:53