【问题标题】:Match key ib Hashmap using arraylist使用arraylist匹配Hashmap中的键
【发布时间】:2016-02-13 17:43:01
【问题描述】:

您好,我有一个包含日期的数组列表

ArrayList 日期 = new ArrayList();

我有类似的日期列表:

All dates between:2015-10-29
All dates between:2015-10-30
All dates between:2015-10-31
All dates between:2015-11-01
All dates between:2015-11-02
All dates between:2015-11-03

我有一个类似 Hashmap 的东西

HashMap<String,String> segCount=userSegmentDAO.getDateWiseCount(user.getOrgId(), startDate, end_Date,fromDate,endDate);

我在哪里获得价值,比如

2015-10-29   6
2015-10-31   3
2015-11-02   5

这里没有我想要的,我一直遍历数组列表直到最后,并且想要与 hashmap 进行比较,如果 hash map conatian 该日期作为键,然后保留它,否则将该日期作为键放在 hashmap 中并放置 0 作为值.

【问题讨论】:

  • containsKey() 不工作吗?
  • 为什么您的地图映射来自 String 而不是来自 Date?

标签: java arraylist hashmap


【解决方案1】:
for (String each: dates ){
            if(!segCount.containsKey(each)){
                segCount.put(each, "0");
            }
        }

但是,最好使用 Date 而不是 String 作为 Map 键和数组元素。

【讨论】:

    【解决方案2】:

    或者如果你使用 java8

    dates.stream()
                .filter(dateString -> !segCount.containsKey(dateString))
                .forEach(dateString -> segCount.put(dateString, "0"));
    

    【讨论】:

      【解决方案3】:

      在 Java 8 中你可以这样做

      for (String s : dates)
          segCount.putIfAbsent(s, "0");
      

      【讨论】:

        猜你喜欢
        • 2012-04-15
        • 1970-01-01
        • 2021-05-31
        • 2015-04-22
        • 1970-01-01
        • 1970-01-01
        • 2016-07-21
        • 2011-01-01
        • 2016-02-14
        相关资源
        最近更新 更多