2016-08-15 130 views
5

我有一些收集List<Map<String, Object>>,需要使用Java 8 lambda表達式進行過濾。 我將收到帶有必須應用過濾標準的標誌的JSON對象。如果沒有收到JSON對象,則不需要過濾。Java 8過濾條件並收集自定義地圖

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()); 

回答

9

只是檢查,你是否需要應用過濾器或沒有再使用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()); 
} 
4

試試這個:

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()) ; 
} 
+4

在Java 9中,您可以用Map.of()替換糟糕的內部類構造。 –

+0

@BrianGoetz很高興認識你!我在實踐中閱讀Java併發性,我喜歡它! –

+0

@DavidPérezCabrera或不等待java-9並使用guava ImmutableMap.of() – Eugene