对于以下描述的需求,从性能的角度来看,按照业务逻辑对列表进行迭代的最佳方法是什么

问题描述 投票:0回答:1

我有一个实体列表。这些是数据库的响应。我还有另一个清单。在实体列表中,每个实体对象都有一个称为id的文件。这些id总是按升序排列。我需要按照long列表中给出的顺序遍历实体列表。另外,我需要维护另一个响应对象列表,该列表将比实体列表中的字段多一些。我也不能使用瞬态。下面的代码将给您一个想法。

public List<ResponseObject> convert(List<EntityObject> entityList, List<Long> orderedIdList) {

    List<ResponseObject> responseList = new ArrayList<>();
    for (EntityObject object : entityList) {
        ResponseObject responseObject = new ResponseObject();
        responseObject.someSettermethod(object.someGettermethod());
        /* other setters in responseObject which are not present in the entity object */
        responseObject.otherSetters("some value"); 
        responseList.add(responseObject);
    };
    return sortInOrder(responseList, orderedIdList);
}

private List<ResponseObject> sortInOrder(List<ResponseObject> responseList,List<Long> orderedIdList) {
    List<ResponseObject> finalList = new ArrayList<>();
     for(Long id : orderedIdList){
         for(ResponseObject response : responseList){
             if(response.getId().equals(id)){
                 finalList.add(response);
             }
         }
     }
    return finalList;
}

这是目前的实现方式。我想知道是否有更好的方法来增强性能以实现相同的输出。

java performance java-ee
1个回答
0
投票

如果这些列表不是huge(就像成千上万的条目一样),我将不必担心性能。这样做是合理的,只要您不满足任何特定的性能要求,就无论如何都不应针对性能优化代码。另一方面,您可以优化代码以提高可读性

  • 通过使用比较器对列表进行排序
  • 通过使用streams API来减少方法的深度。

可以使用排序列表来构造比较器,然后从您的resultList中比较ID的索引。

比较器看起来可能与此类似:

private static class IndexComparator implements Comparator<Long> {
    private final List<Long> order;

    private IndexComparator(List<Long> order) {
        this.order = order;
    }

    @Override
    public int compare(Long id1, Long id2) {
        return Comparator.comparingLong(order::indexOf).compare(id1, id2);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.