• 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,效率高。

     
     
     
  • 相关阅读:
    ubuntu 14.04下使用fcitx时将caps lock映射为ctrl
    php多进程、IPC和事件驱动
    [轉載]【京都动画统治世界】短篇科幻小说《2134动漫奇缘》
    [日语]每日笔记
    [转载]C++的顺序点(sequence point)和副作用(side effect)
    [转载]Best Practices for Speeding Up Your Web Site
    [系统]安装fedora 19
    阿里云服务上面部署redis + 本地Redis客户端连接方法 + 配置redis服务
    linux [Centos7]搭建PHP的RabbitMQ环境
    linux vim常用操作
  • 原文地址:https://www.cnblogs.com/qqzhulu/p/10339937.html
Copyright © 2020-2023  润新知