【问题标题】:Java 8 Filtering with condition and collecting custom MapJava 8 过滤条件和收集自定义地图
【发布时间】:2016-12-21 18:11:14
【问题描述】:

我有一些集合 List<Map<String, Object>> 需要使用 Java 8 lambda 表达式进行过滤。 我将收到带有必须应用过滤条件的标志的 JSON 对象。如果没有收到 JSON 对象,则不需要过滤。

protected List<Map<String, Object>> populate(List<SomeObject> someObjects, String string) {
    taskList.stream()
            // How to put condition here? Ho to skip filter if no filter oprions are received?
            .filter(someObject -> (if(string != null) someobject.getName == string))
           // The second problem is to collect custom map like
            .collect(Collectors.toMap("customField1"), someObject.getName()) ... // I need somehow put some additional custom fields here
}

现在我正在收集这样的自定义地图:

Map<String, Object> someMap = new LinkedHashMap<>();
someMap.put("someCustomField1", someObject.field1());
someMap.put("someCustomField2", someObject.field2());
someMap.put("someCustomField3", someObject.field3());

【问题讨论】:

    标签: java lambda filter java-8 java-stream


    【解决方案1】:

    只需检查,是否需要应用过滤器,然后使用filter 方法或不使用它:

    protected List<Map<String, Object>> populate(List<SomeObject> someObjects, String string) {
        Stream<SomeObject> stream = someObjects.stream();
        if (string != null) {
             stream = stream.filter(s -> string.equals(s.getName()));
        }
        return stream.map(someObject -> {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("someCustomField1", someObject.Field1());
            map.put("someCustomField2", someObject.Field2());
            map.put("someCustomField3", someObject.Field3());
            return map;
        }).collect(Collectors.toList());
    }
    

    【讨论】:

      【解决方案2】:

      试试这个:

      protected List<Map<String, Object>> populate(List<SomeObject> someObjects, String string) {
          return someObjects.stream()
                  .filter(someObject -> string == null || string.equals(someObject.getName()))
                  .map(someObject -> 
                    new HashMap<String, Object>(){{
                          put("someCustomField1", someObject.Field1());
                          put("someCustomField2", someObject.Field2());
                          put("someCustomField3", someObject.Field3());
                    }})
                  .collect(Collectors.toList()) ;
      }
      

      【讨论】:

      • 在 Java 9 中,您可以用 Map.of() 替换糟糕的内部类构造。
      • @BrianGoetz 很高兴见到你!我在实践中阅读了 Java 并发,我喜欢它!
      • @DavidPérezCabrera 或者不要等待 java-9 并使用 guava ImmutableMap.of()
      • @Brian Goetz:问题的代码使用了LinkedHashMap,我想Map.of(…) 的结果不会提供相同的有序性。
      猜你喜欢
      • 1970-01-01
      • 2015-07-26
      • 2018-02-07
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 2016-01-25
      • 1970-01-01
      相关资源
      最近更新 更多