英文:
Is there any way to improve the performance of the below code?
问题
代码正在比较两个`list`的代码。第一个`list`来自api调用,第二个来自数据库。我使用两个循环遍历这两个list并进行比较,将共同的部分添加到一个新的list中。第一个list大约包含800个数据,而第二个list(来自数据库)包含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 = "这个查询从数据库获取代码";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet result = statement.executeQuery();
while (result.next()) {
for (AllowedCodes a : old_codes_list) {
if (a.getCodeValue().equalsIgnoreCase(result.getCodeValue())) {
new_codes_list.add(a);
}
}
}
}
}
英文:
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);
}
}
}
}
}
答案1
得分: 1
将列表复制到 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);
}
}
英文:
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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论