1

In a scenario where a map of coreValues contains: Value 1 -> List("1", "2", null, "3") I want to filter out null values from the list, i have below solution:

 boolean hasCoreValues = false;
 Optional<Map<String,List<String>> coreValues = buildCoreValuesMap(core); 
 hasCoreValues = corevalues.map(cv -> {
    final List<String> values = cv.getOrDefault(value, Immutable.of())
    values.removeAll(singletonList(null));
    return !values.isEmpty();
 }).orElse(false);



public Optional<Map<String, List<String>>> buildCoreValuesMap(String core) {
        return Optional.ofNullable(context.selectFrom(DataStorage)
                .where(DataStorage.CORE.in(core))
                .fetchGroups(DataStorage.CORE,
                        DataStorage.VALUES));
    }

is there a better way to do it without going thru the list again to remove the null?

MikasaAckerman
  • 531
  • 5
  • 17
  • values.removeAll(singletonList(null)) i am using the method to remove null, its not a duplicate question. My question is to how to remove null without iterating twice. – MikasaAckerman Oct 07 '19 at 23:46
  • 1
    can you show the code of this method `buildCoreValuesMap` ? – Ryuzaki L Oct 07 '19 at 23:51

1 Answers1

4

If you just want to remove all null in List<String> from coreValues, then just iterate Map and remove all null values from list using removeIf

coreValues.forEach((k,v)-> v.removeIf(Objects::isNull));
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98