2

I have the following code in Java 7:

List<Integer> idMappers= new ArrayList<>();

//getting information from a Map<String, List<String>>
List<String> ids= idDataStore.lookupId(id); 

 for (int i = 0; i < ids.size(); i++) {

 //getting information from a Map<String, List<Integer>>
  List<Integer> mappers= idDataStore.lookupMappers(ids.get(i));

  if (mappers!= null) {
    for (int j = 0; j < x.size(); j++) {
      idMappers.add(mappers.get(j));
    }
  }
}

I'm trying to change this to Streams

List<Integer> idMappers= new ArrayList<>();
idDataStore.lookupIdMappings(id).forEach(id-> {
  idDataStore.lookupSegments(id).forEach(mapper->{
    idSegments.add(segment);
  });
});

My problem is idDataStore.lookupSegments(id) can sometimes throw null so my stream is breaking. How Can I do a null check in Stream?

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
edwin
  • 7,985
  • 10
  • 51
  • 82
  • try this one `idDataStore.lookupIdMappings(id) .stream() .map(i -> idDataStore.lookupSegments(id)) .filter(Objects::nonNull) .forEach(s -> s.forEach(idSegments::add));` – Hadi J Oct 02 '18 at 18:28

2 Answers2

2

Firstly, the variable (id) using in lambda cannot have the same name as the variable in the very same scope of the method.

Lambda expression's parameter id cannot redeclare another local variable defined in an enclosing scope.

I see you work with nested for looping, why to not use the Stream::flatMap?

idDataStore.lookupIdMappings(id).stream()
                                .map(i -> idDataStore.lookupSegments(id))
                                .filter(Objects::nonNull)
                                .flatMap(List::stream)
                                .collect(Collectors.toList());
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
1

Just add idDataStore.lookupSegments(id).stream().filter(Objects::notNull) to you nested loop.

However what you have is a side effect(see side effect section) and it is not recommended way to populate idMappers list. Let me try to convert using flatMap

List<Integer> idMappers = idDataStore.lookupIdMappings(id)
           .stream() // stream of LookupId's
           .flatMap(idMapping -> idDataStore
                                .lookupSegments(id)
                                .stream()
                                .filter(Objects::notNull)
                                // get stream of corresponding lookupSegments
                                // and filter out all nulls
           )
           .collect(Collectors.toList());

I hope this helps.

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
  • I tried that from this https://stackoverflow.com/a/47082894/1450401 but didn't help throwing the same error – edwin Oct 02 '18 at 14:53