[英]Is there any way to improve the performance of the below code?
代码正在比较 2 个代码list
。第一个list
来自 api 调用,第二个来自数据库。我使用 2 个循环来迭代列表并比较它们,并将公共添加到新列表中。第一个列表包含大约 800数据和第二个列表(来自 db)包含 150 个数据。有没有办法提高此代码的性能。我不允许在AllowedCodes Class
进行任何更改。使用嵌套循环是否会影响给定数据量的性能?
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);
}
}
}
}
}
将列表复制到HashMap
,将小写时具有相同代码值的AllowedCodes
分组:
Map<String, List<AllowedCodes>> map =
old_codes.stream().collect(groupingBy(a -> a.getCodeValue().toLowerCase()));
然后,在你的 while 循环中:
while(result.next()) {
String resultCodeValue = result.getCodeValue().toLowerCase();
for (AllowedCodes a : map.getOrDefault(resultCodeValue, Collections.emptyList())) {
new_codes_list.add(a);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.