【问题标题】:Filter HashMap based on keys return list根据键返回列表过滤HashMap
【发布时间】:2020-01-06 21:28:55
【问题描述】:

我有一个带有键的 HashMap,值是字符串。我想通过以字符串“locationId”开头的键值过滤 HashMap,并将键中的值返回到字符串数组列表。 这就是 HashMap 的填充方式:

HashMap<String, String> hm = new HashMap<String, String>();
hm.put("locationId2", rs.getString("ORG_Id"));
hm.put("locationType2", rs.getString("ORG_Type"));
hm.put("StartDate2", rs.getString("START_DT_TM_GMT"));


hm.put("locationId3", rs.getString("ORG_Id"));
hm.put("locationType3", rs.getString("ORG_Type"));
hm.put("StartDate3", rs.getString("START_DT_TM_GMT"));


hm.put("locationId4", rs.getString("ORG_Id"));
hm.put("locationType4", rs.getString("ORG_Type"));
hm.put("StartDate4", rs.getString("START_DT_TM_GMT"));


hm.put("locationId5", rs.getString("ORG_Id"));
hm.put("locationType5", rs.getString("ORG_Type"));
hm.put("StartDate5", rs.getString("START_DT_TM_GMT"));

我需要一个数组列表中的 ORG_Id 值。

List<String> facilityIds = hm.entrySet().stream().filter(x -> x.getKey().startsWith("locationId")).collect(map -> map.values());

我找不到可以将值放入字符串列表的位置。 编译错误是它无法识别 values() 方法。

更新 还尝试将过滤后的 Hashmap 放入另一个 HashMap 中,如下所示:

HashMap<String, String>  facilityIds = currentOperatingSchedules.entrySet().stream().filter(map -> map.getKey().startsWith("locationId")).collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));

但是得到它不识别getKey()getValue()

的编译错误

【问题讨论】:

  • 我相信我有一个解决方案。但是你想要ArrayList 还是map(就像你第二次尝试的那样)?

标签: java arraylist lambda hashmap


【解决方案1】:

这应该可行。它的工作原理如下:

  1. 获取地图的entrySet 并创建流。
  2. 过滤以locationId开头的键
  3. 并将这些值收集到一个列表中。

         List<String> list = hm.entrySet().stream()
                      .filter(e->e.getKey().startsWith("locationId"))
                      .map(e->e.getValue())
                      .collect(Collectors.toList());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 2021-05-03
    • 2018-07-31
    • 2015-05-17
    • 2020-09-11
    相关资源
    最近更新 更多