java - 根据键返回列表过滤HashMap

标签 java arraylist lambda hashmap

我有一个 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()

最佳答案

这应该有效。其工作原理如下:

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

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

关于java - 根据键返回列表过滤HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59619217/

相关文章:

java - 在 Java 中运行 Daemon 类时出错?

java - 仅在一个目录的命令行中设置 Java 路径

java - final ArrayList 是什么意思?

c++ - 如何使用自定义删除器复制 unique_ptr

java - Android 当多个任务完成时执行

java - (如何?)我可以用多个正交接口(interface)参数化 Java 类吗?

Java - 删除ArrayList中的项目

java - 设置ArrayLists的ArrayList的初始容量

c# - LINQ 加入多个字段

java - 如何在 Java 8 中迭代 lambda 过滤器流中的列表?