3

I have a list huge list of strings. The strings are either "ACCEPTED", "OK" or " NOT OK".

If list contains one ACCEPTED the final value should be ACCEPTED, irregardless of the other values. If there is no ACCEPTED but there is an OK, the final value should be OK. If neither of them appear, the final value should be NOT OK.

I can use String.contains() method to check the values contains certain string, but I have a huge list. Therefore I am afraid it will cause the performance issue.

if(s.contains(("ACCEPTED"))) {
               value= "ACCEPTED";
               break;
            } else if(s.contains(("OK"))) {
                value= "OK";
                break;
            } else {
                value= "NOT OK";
            }

Will this method work for huge lists, or do I need to use something else?

WhoAmI
  • 57
  • 7

1 Answers1

1

This is basically a question if ArrayList.contains() is quick enough. This has already been answered on SO here:

Time complexity of ArrayList.contains() is O(n). In layman's terms, performance scales linearly. A list with twice as many items will take twice the time to execute. This is almost as good as it gets and IMO you should not be worried about performance.

But as tom said, it's better to use a Set which by definition does not store duplicate values.

EDIT:

Here is an example of working code, you can also test it here:

import java.util.*;

class myCode
{
    public static void main (String[] args) throws java.lang.Exception
    {
        ArrayList<String> testList = new ArrayList<String>(); 
        String s1 = new String ("ACCEPTED");
        String s2 = new String ("OK");
        String s3 = new String ("NOT OK");


        testList.add(s1);
        testList.add(s2);
        testList.add(s3);


        String status= "";

        if(testList.contains("ACCEPTED")) {
             status= "ACCEPTED";
        }
        else if(testList.contains("OK")) {
            status= "OK";
        } 
          else {
            status= "NOT OK";
         }
        System.out.println(status);

    }
}
Hami
  • 704
  • 2
  • 9
  • 27
  • But always it returns NOT OK, As per my requirement, it should return ACCEPTED if any one of the Status values is ACCEPTED. Here is my code: Status s1 = new Status ("ACCEPTED"); Status s2 = new Status ("OK"); Status s3 = new Status ("NOT OK"); testList.add(s1); testList.add(s2); testList.add(s3); String status= ""; if(testList.contains("ACCEPTED")) { status= "ACCEPTED"; } else if(testList.contains("OK")) { status= "OK"; } else { status= "NOT OK"; } – WhoAmI Jun 10 '17 at 23:35