zoukankan      html  css  js  c++  java
  • 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,效率高。

     
     
     
  • 相关阅读:
    lhgdialogv3.13 使用点滴
    CheckBoxList 取值 及选中相关用法
    repeater 及 gridview 中绑定短日期
    数据库中日期大小的判断
    父子不同窗口间刷新传值
    子级Repeater获取父级Repeater绑定项的值
    vs.net 2010 web 项目中使用 webservice
    web打印实现方案 Lodop6.034 使用方法总结
    用 showModalDialog 方法回传数据到父页中去
    vs.net2010中使用 Ajax Control Toolkit
  • 原文地址:https://www.cnblogs.com/qqzhulu/p/10339937.html
Copyright © 2011-2022 走看看