【问题标题】:Filter Map<String,List<Object>> Using Java Streams使用 Java 流过滤 Map<String,List<Object>>
【发布时间】:2022-01-17 05:29:53
【问题描述】:
class Custom{
   String itemId,
   long createdTS
   //constructor
   public Custom(String itemId,long createdTS)
}

我有两张地图

Map<String,Long> itemIDToFilterAfterTS;
Map<String,List<Custom>> itemIDToCustoms;

我想使用 java 流的项目的第一个映射 itemIDToTimestampMap 值过滤第二个映射 itemIDToCustoms 值。 例如。

itemIDToFilterAfterTS = new HashMap();
itemIDToFilterAfterTS.put("1",100);
itemIDToFilterAfterTS.put("2",200);
itemIDToFilterAfterTS.put("3",300);

itemIDToCustoms = new HashMap();
List<Custom> listToFilter = new ArrayList();
listToFilter.add(new Custom("1",50));
listToFilter.add(new Custom("1",90));
listToFilter.add(new Custom("1",120));
listToFilter.add(new Custom("1",130));
itemIDToCustoms.put("1",listToFilter)

现在我想使用 java 流并希望得到过滤的结果映射,getKey("1") 为它提供已创建的自定义对象的过滤列表 TS > 100(将从 itemIDToFilterAfterTS.getKey("1") 获取 100)

Map<String,List<Custom>> filteredResult will be 
Map{
   "1" : List of (Custom("1",120),Custom("1",130))
}  

【问题讨论】:

    标签: java hashmap java-stream


    【解决方案1】:

    您可以像这样使用Map#computeIfPresent 方法:

    如果键已经与值关联,则允许您计算指定键的映射值

    public Object computeIfPresent(Object key,BiFunction remappingFunction)
    

    所以你可以像这样执行它:

    itemIDToFilterAfterTS.forEach((key, value) ->
                itemIDToCustoms.computeIfPresent(key, (s, customs) -> customs.stream()
                        .filter(c -> c.getCreatedTS() > value)
                        .collect(Collectors.toList())));
    

    【讨论】:

      【解决方案2】:

      这里的流语法有点过分了

      itemIDToCustoms = itemIDToCustoms.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(),
                  e -> e.getValue().stream().filter(val -> val.createdTS > itemIDToFilterAfterTS.get(e.getKey())).collect(Collectors.toList())));
      

      使用 for 循环 + 流更具可读性

      for (Map.Entry<String, List<Custom>> e : itemIDToCustoms.entrySet()) {
          long limit = itemIDToFilterAfterTS.get(e.getKey());
          List<Custom> newValue = e.getValue().stream().filter(val -> val.createdTS > limit).collect(Collectors.toList());
          itemIDToCustoms.put(e.getKey(), newValue);
      }
      

      【讨论】:

      • 感谢您的帮助,非常感谢..它对我有用!
      猜你喜欢
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 2020-01-26
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多