Home > Back-end >  Java 8 stream condition for null values
Java 8 stream condition for null values

Time:11-14

I am using Java 8 stream

executeRequest(requestId).stream()
        .map(d-> (Response) d).collect(Collectors.toList());

the Response object is like this

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Response {

  String title;
  String id;
}

when the responses are null, I am getting an error because it is trying to collect null values in a list, I want to have a condition that when title is null, stream does not continue, or any thing that helps me to handle it

CodePudding user response:

I think you need some think like this:

List<Response> response = executeRequest(requestId).stream()
    .filter(Objects::nonNull)                    // filter the object if not null
    .map(Response.class::cast)                   // cast the object
    .filter(r -> Objects.nonNull(r.getTitle()))  // filter by title if not null
    .collect(Collectors.toList());

CodePudding user response:

I would suggest using.filter()

Try out this

executeRequest(requestId).stream()
.filter(Objects::nonNull)
.map(d-> (Response) d)
.filter(resp -> Objects.nonNull(resp.getTitle()))
.collect(Collectors.toList());
  • Related