简体   繁体   English

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

[英]What will be the best way to iterate the list as per business logic from performance point of view for the below described requirement

I have a list of entity. 我有实体清单。 these are the response from db. 这些是数据库的响应。 I have another list of long. 我还有另一个清单。 In the list of entity, each entity object has a filed called id. 在实体列表中,每个实体对象都有一个称为id的文件。 Those id will always be in ascending order.I need to traverse the entity list as per the order given through the list of long. 这些id总是按升序排列。我需要按照long列表中给出的顺序遍历实体列表。 Also I need to maintain another list of response object which will have few more fields than what we have in the entity list. 另外,我需要维护另一个响应对象列表,该列表将比实体列表中的字段多一些。 I can not use transient also. 我也不能使用瞬态。 The code below will give you an idea. 下面的代码将给您一个想法。

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

This is how it has been implemented for now. 这是目前已实施的方式。 I would like to know if there is any better approach to enhance the performance to achieve the same output. 我想知道是否有更好的方法来增强性能以实现相同的输出。

If these lists aren't huge (like in many many thousands of entries), I wouldn't worry about performance. 如果这些列表不是很大 (就像成千上万的条目一样),我将不必担心性能。 It's reasonable as it is and as long as you don't fail any specific performance requirements you shouldn't optimize your code for performance anyway. 这样做是合理的,只要您不满足任何特定的性能要求,就无论如何都不应针对性能优化代码。 You could on the other hand optimize your code for readability 另一方面,您可以优化代码以提高可读性

  • by using a comparator to sort your list 通过使用比较器对列表进行排序
  • by using the streams API to reduce the depth of your methods. 通过使用streams API来减少方法的深度。

The comparator could be constructed using the ordering list and then comparing the indices of the ids from your resultList. 可以使用排序列表构造比较器,然后从您的resultList中比较ID的索引。

The comparator could look similar to this one: 比较器看起来可能与此类似:

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

The sortInOrder method can be done faster than O(N^2): sortInOrder方法可以比O(N ^ 2)更快地完成:

Assuming, Ids are unique (let me know if its a wrong assumption): 假设ID是唯一的(如果错误假设,请告知我):

Idea: 理念:

  1. Create a map of Id to responseObject by iterating over the response list O(n). 通过遍历响应列表O(n),创建一个ID到responseObject的映射。
  2. Iterate over orderedIdList and check for id in map, if the id exists, add the value to response Object. 遍历orderedIdList并检查地图中的id,如果该id存在,则将该值添加到响应对象。
private List<ResponseObject> sortInOrder(List<ResponseObject> responseList,List<Long> orderedIdList) {
    List<ResponseObject> finalList = new ArrayList<>();
    Map<Long, ResponseObject> map = responseList.stream().collect(Collectors.toMap(ResponseObject::getId, respObj -> respObj));
    for(Long id : orderedList) {
      if(map.containsKey(id)) {
         finalList.add(map.get(id));
      }
    }
    return finalList;
}

If you use map instead of a list like below, you can do it with complexity O(n) instead of O(n2) 如果使用map而不是下面的列表,则可以使用O(n)而不是O(n2)来完成

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

        Map<Long, ResponseObject> responseMap = new HashMap<Long, ResponseObject>();
        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");
            responseMap.put(responseObject.getId(), responseObject);
        };
        return sortInOrder(responseMap, orderedIdList);
    }

    private List<ResponseObject> sortInOrder( Map<Long, ResponseObject> responseMap, List<Long> orderedIdList) {
        List<ResponseObject> finalList = new ArrayList<>();
        for(Long id : orderedIdList){
            finalList.add(responseMap.get(id));
        }
        return finalList;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将业务与Presentation Logic分开的最佳方式? - Best way to separate Business from Presentation Logic? 迭代列表的最佳方法是什么 - What is the best way to iterate over list 在 ItemProcessor 中实现多个业务逻辑的最佳方法 - Best way to implement multiple business logic in ItemProcessor 是否可以通过下面描述的方式从firefox扩展连接到java - Is it possible to connect to java from a firefox extension in the way described below 从数据库迭代和处理整个表的最佳方法是什么? - What is the best way to iterate and process an entire table from database? 通过@Inject将业务逻辑暴露给宁静服务的最佳方式 - Best way to expose business logic to restful services via @Inject 为不同的参数和类型编写具有相同业务逻辑的方法的最佳方法? - Best way to write method with same business logic for different parameters and type? 从下到上迭代元素列表的最佳方法是什么? - Which is the best way to iterate the list of elements from bottom to up? 从List中删除对象的最佳方法是什么 - What is the best way to remove objects from a List 从大型集合中获取重复项的最佳性能方式是什么<string> ?</string> - What it is the best performance way to grab duplicates from a large Set<String>?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM