【问题标题】:how to get a value and an array present inside a list如何获取列表中存在的值和数组
【发布时间】:2015-05-05 10:54:06
【问题描述】:

我想从列表中的数组中获取一个值。每个列表值都包含一个数组,我想从该数组中获取一个单值。

Mail.java

properties = new Properties("server_url.properties");
    dataAccess = new DataAccess(properties);
    List<Map<String,String>> resp = new ArrayList<Map<String,String>>() ;
    List<Map<String,String>> obj = new ArrayList<Map<String,String>>() ;
        resp=dataAccess.getApplications();
        obj=dataAccess.getServers();
            //System.out.println(resp.get(0));

            MailServer sender = new MailServer(Constants.setFrom, Constants.setPassword);

            try {
            sender.sendMail("Demo Apps & Server Status","The Following Applications are DOWN" + '\n'+
                    '\n' + resp.get(0) + '\n'+
                    '\n'+ "The Following servers are DOWN" +'\n'
                    + '\n' + obj.get(2)
                    ,Constants.setFrom,Constants.emailTO);
        }
               catch (Exception e) {
             e.printStackTrace();
             System.out.println("Email was not sent...");

        }  

            System.out.println("Email Sent Succesfully...");

        }

如果我运行上面的代码,我会得到以下列表值

输出

{DataBase=Oracle, Links=192.168.215.158:1521:sscdb01, status=UP, 192.168.215.158:151:sscdb01=UP, name=Claim Status, WebServices=}
{Links=https://mobile.infotech.com:8090, status=UP, ssl_exp_date=Mon Apr 18 14:42:45 IST 2016, https://mobile.infotech.com:8090=UP, name=com}

从上面的值我只想得到两个值 - name 和 Status 值而不从列表值中获取所有值

【问题讨论】:

    标签: java arrays list collections


    【解决方案1】:

    只需在所需键上调用 get 即可获取 Map 中的值(即 not 数组)。

    例如:

    resp.get(0).get("name")
    resp.get(0).get("status")
    

    我强烈建议检查 null 值。类似于:

    // checking: list not empty, index x < list size, indexed item at x not null
    if (!resp.isEmpty() && resp.size() > x && resp.get(x) != null)) {
        // checking: value for key "name" not null
        if (resp.get(x).get("name") != null) {
             String foo = resp.get(x).get("name");
        }
    }
    

    ... 其中x 是您想要的List 索引。可以通过分配给引用而不是一遍又一遍地调用get 来改进上面的示例。

    【讨论】:

      【解决方案2】:

      你应该使用类似的东西

       resp.get(0).get(key);
      

      obj 也是如此

      【讨论】:

        【解决方案3】:
        resp.get(index).get("name")
        resp.get(index).get("status")
        

        【讨论】:

        • 对你的答案做一点解释,对提问者和其他后来找到这个答案的人都有用。
        猜你喜欢
        • 2016-05-29
        • 2019-09-11
        • 1970-01-01
        • 2018-01-28
        • 1970-01-01
        • 2013-04-17
        • 2020-09-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多