简体   繁体   English

根据键返回列表过滤HashMap

[英]Filter HashMap based on keys return list

I have a HashMap with key, values that are strings.我有一个带有键的 HashMap,值为字符串。 I would like to filter the HashMap by the key values that start with the string " locationId " and return the values in the keys to an array list of strings.我想通过以字符串“ locationId ”开头的键值过滤 HashMap 并将键中的值返回到字符串数组列表。 This is how the HashMap is populated:这是 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"));

I need the ORG_Id values in an arraylist.我需要数组列表中的 ORG_Id 值。

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

I can't find where I can put the values into a string list.我找不到可以将值放入字符串列表的位置。 The compile error is that it does not recognize the values() method.编译错误是它无法识别values()方法。

UPDATE Also tried putting the filtered Hashmap into another HashMap like this:更新还尝试将过滤后的 Hashmap 放入另一个 HashMap 中,如下所示:

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

But get the compilation error that it does not recognize getKey() and getValue()但是得到它无法识别getKey()getValue()的编译错误

This should work.这应该有效。 It works as follows:它的工作原理如下:

  1. Get the entrySet of the map and create a stream.获取地图的entrySet并创建一个流。
  2. filter on the key that starts with locationId过滤以locationId开头的键
  3. And collect those values into a list.并将这些值收集到一个列表中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM