• java Map代替List在for循环中的应用


    例:有数据表:express

    对list集合:通过code获取name(orderController)

    方式1:

    (先查出数据表express中所有的对象List<Express>,在List<ExpressStatus>的遍历中,通过获取code,再获取name值,循环较多,i*j次)

    controller:

    List<Express> nameList = null;
    try {
    nameList = expressService.getAllName();
    } catch (Exception e) {
    return new APIResult(GlobalConstantsUtil.LOGIN_SESSION_INVALID, "获取物流公司对象失败");
    }
    List<ExpressStatus> list = null;
    try {
    list = expressStatusService.getByAllNo(orderId);
    } catch (Exception e) {
    return new APIResult(GlobalConstantsUtil.GENERAL_ERROR, "获取物流数据失败");
    }
     
    for (int i = 0; i < list.size(); i++) {
     
    ExpressStatus expressStatus = list.get(i);// achieve ExpressStatus object
    String company = expressStatus.getCom();// achieve company
     
    for (int j = 0; j < nameList.size(); j++) {
    Express express = nameList.get(j);
    String code = express.getCode();
    if (code.equals(company)) {
    companyName = express.getName();
    }
    }
    }
     
    方式二:
    (采用map方式,将查出的list对象放入map对象,在在List<ExpressStatus>的遍历中,通过获取code,再获取name值,循环少,i次)

    List<Express> nameList = null;
    try {
    nameList = expressService.getAllName();
    } catch (Exception e) {
    nameList = null;
    }
    // create List<ExpressStatus> object
    List<ExpressStatus> list = null;
    try {
    list = expressStatusService.getByAllNo(orderId);
    } catch (Exception e) {
    return new APIResult(GlobalConstantsUtil.GENERAL_ERROR, "获取物流数据失败");
    }
    if (list == null) {
    return new APIResult(GlobalConstantsUtil.GENERAL_ERROR, "获取物流数据失败");
    }
    // create HashMap and add data
    Map<String, String> expMap = new HashMap<String, String>();
    if (nameList == null) {
    nameList = new ArrayList<Express>();
    }
    for (int i = 0; i < nameList.size(); i++) {
    expMap.put(nameList.get(i).getCode(), nameList.get(i).getName());
    }

    for (int i = 0; i < list.size(); i++) {
    ExpressStatus expressStatus = list.get(i);// achieve ExpressStatus object

    String company = expressStatus.getCom();// achieve company

    String eCompanyName = null;
    eCompanyName = expMap.get(company);// achieve eCompanyName from Map

    }

    使用Map,通过键值对,获得键:code,使用方法:map.get(key)获取值,可直接获取name,效率高。

     
     
     
  • 相关阅读:
    进阶学习项目实战链接
    Django与数据库操作
    xadmin的使用
    Django 常见的异常
    网站 安全 ---- 常见的 web 攻击
    nodejs--vue
    ECMAScript 6 简介
    Django -- DRF 认证流程
    Django -- 缓存
    Django --- celery异步任务与RabbitMQ模块
  • 原文地址:https://www.cnblogs.com/qqzhulu/p/10339937.html
Copyright © 2020-2023  润新知