2016-08-15 19 views
5

Mam pewną kolekcję List<Map<String, Object>>, którą należy filtrować opcjonalnie za pomocą wyrażeń lambda w języku Java 8. Otrzymam obiekt JSON z flagami, które kryteria filtrowania muszą zostać zastosowane. Jeśli obiekt JSON nie zostanie odebrany, nie jest wymagane filtrowanie.Java 8 Filtrowanie ze stanem i zbieranie niestandardowej mapy

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 
} 

Teraz mam zwyczaj zbierania map tak:

Map<String, Object> someMap = new LinkedHashMap<>(); 
      someMap.put("someCustomField1", someObject.Field1()); 
      someMap.put("someCustomField2", someObject.Field2()); 
      someMap.put("someCustomField3", someObject.Field3()); 

Odpowiedz

9

Wystarczy sprawdzić, czy trzeba zastosować filtr lub nie, a następnie użyć metoda filter lub nie używaj go:

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

Spróbuj z tym:

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

W Javie 9 można zastąpić okropną wewnętrzną konstrukcję klasą Map.of(). –

+0

@BrianGoetz miło cię "poznać"! W praktyce czytam współbieżność Java i uwielbiam to! –

+0

@ DavidPérezCabrera lub nie czekaj na java-9 i używaj guava ImmutableMap.of() – Eugene

Powiązane problemy