The codes is comparing 2 list of codes.First list is got from api call and second from database.I am using 2 loops to iterate over the list and compare them ,and add the common to a new list.The first list contains around 800 data and second list(from db) contains 150 data.Is there any way to improve the performance of this code.I am not allowed to make any changes in AllowedCodes Class.Does using nested loops affect performance with the given amount of data?
public class AllowedCodes { private String codeValue=""; public String getCodeValue() { return codeValue; } public void setCodeValue(String codeValue) { this.codeValue = codeValue; } } public class CheckCodes { public static void main(String[] args) { List<AllowedCodes> old_codes_list=getListOfOldCodes(); List<AllowedCodes> new_codes_list=new ArrayList<>(); String sql = "This query gets the codes from database"; PreparedStatement statement = connection.prepareStatement(sql); ResultSet result = statement.executeQuery(); while(result.next()) { for(AllowedCodes a:old_codes){ if(a.getCodeValue().equalsIgnoreCase(result.getCodeValue())){ new_codes_list.add(a); } } } } }
HashSetinstead of a list forold_codes_list. (Store and compare codes as lower case to ignore the original casing.)HashSet. Or some other data structure, like a Trie.forloop with aset.contains(...)which runs in constant time (amortized). (You'll do 1 linear operation, instead of hundreds.)getHashCode()value, so it doesn't have to callequals()on every item in the collection. You probably don't need to worry about the implementation details, though, so much as the fact thatcontains()is aO(1)operation, so creating a Map and checking all the items becomes aO(n)-complexity operation instead ofO(n²).