1

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

7
  • 1
    not quite sure on ur specification, should the thing be skipped or the whole stream be aborted? for former, use .filter(r -> r.title != null). for latter u might want to use .takeWhile(r -> r.title != null) or similar. Commented Nov 14, 2022 at 9:00
  • @Zabuzard as the r value is an object at first and in map I am converting it to Response, it hasn't a title option to check if it is null or not in the filter Commented Nov 14, 2022 at 9:05
  • You can put the filter after the map Commented Nov 14, 2022 at 9:11
  • @TimMoore it doesn't recognize the value again Commented Nov 14, 2022 at 9:13
  • 2
    thats also the wrong syntax for a lambda. u have to write .filter(r -> r.title != null). carefully read the suggestions. Commented Nov 14, 2022 at 9:53

2 Answers 2

3

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());
Sign up to request clarification or add additional context in comments.

Comments

3

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

3 Comments

note that this only ensures that the Response object itself is not null. OP asked for the title (a field of Response) not being null.
it doesn't work. executeRequest is returning a list of objects, the response is not null itself but the parameters inside it may be null, and I want to filter them
@Tindona Updated lambda

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.