-2

I have the following for loop, where the StringList is

List<String> stringList= new ArrayList<String>();

for (String elementList : stringList) 
   {
        if (elementList =="string1")
        {
            Key=1;
        }
        else if (elementList =="string2")
        {
            Key=0;
        }
   // do some code here 
   }

If the (stringList) includes 20,000 string words. The repeating of the words "string1" and "string2" is 10,000 for each in (stringList). it takes time to check every word in the for loop.

How can we make the for loop iterate only two times because there are only two types of words which are "string1" and "string2" regardless of it's repeating in the (stringList)

1 Answers1

0

As i said you should use method equals for comparing two strings. And also i think you can use method contains() to check if your list contains some strings

contains(Object o) Returns true if this list contains the specified element.

if (stringList.contains("string1"))
    Key = 1;
if (stringList.contains("string2"))
    key = 2;
user3127896
  • 6,323
  • 15
  • 39
  • 65