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
}
}
}
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With