user14244069
user14244069

Reputation:

Is there any way to improve the performance of the below code?

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);
               }
            }

        }



    }

}

Upvotes: 1

Views: 67

Answers (1)

Andy Turner
Andy Turner

Reputation: 140534

Copy the list into a HashMap, grouping AllowedCodes that have the same code value when lowercased:

Map<String, List<AllowedCodes>> map =
    old_codes.stream().collect(groupingBy(a -> a.getCodeValue().toLowerCase()));

Then, in your while loop:

while(result.next()) {
  String resultCodeValue = result.getCodeValue().toLowerCase();
  for (AllowedCodes a : map.getOrDefault(resultCodeValue, Collections.emptyList())) {
    new_codes_list.add(a);
  }
}

Upvotes: 1

Related Questions