Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ArrayList iteration [closed]

I have an ArrayList which stores Area names. I want to check this list to find whether arbitrary people are from different area. If they are from different area, i take a decision. I achieved this with the following code. Note that area_IdList and area_IdListduplicate are essentially the same ArrayList. Is this code efficient or can anyone suggest more efficient code ? Thanks in Advance.

public List<String> area_IdList = new ArrayList<String>();
public List<String> area_IdListduplicate = new ArrayList<String>();

for (int i = 0; i < area_IdList.size(); i++) 
{  
    for (int k = 1; k< area_IdListduplicate.size(); k++)
    {
        String sa= area_IdListduplicate.get(k);
        String sb= area_IdList.get(i);
        if (!sa.equalsIgnoreCase(sb))
        { 
            some decision
        }
    }             
}
like image 981
kzs Avatar asked Oct 18 '12 06:10

kzs


2 Answers

for (String area : area_IdList) 
{  
    for (String duplicatedArea : area_IdListduplicate)
    {
        if (!area.equalsIgnoreCase(duplicatedArea))
        { 
            // some decision
        }
    }             
}

This is more efficient, goes faster instead of iterating by indexes. So this will check step by step each element in area_IdList with all elements in area_idListduplicate and each time they don't mach, this decision will be made. (If that's what you want achieve)

like image 165
Carnal Avatar answered Oct 24 '22 00:10

Carnal


This is a O(2N) solution at some cost of 2N memory instead of N^2 time and N memory cost. Depends on the number of items that you have, but this solution will cost significantly less than the N^2 solutions.

  Set<String> list=new Set<String>();
  for (String area : area_IdList) 
  {  
    list.add(area.toLowerCase());
  }

  for (String duplicatedArea : area_IdListduplicate)
  {
    if(list.contains(duplicatedArea.toLowerCase())){
      //Do something
    }
  }

As for not using index, see Use Enhanced For Loop Syntax

like image 30
Edison Avatar answered Oct 23 '22 23:10

Edison