javajsonlistiteratorjava-stream

How do I find a specific element in a list of objects?


I parsed all the JSON from /posts at JSONPlaceholder into a list of objects. But I'm having trouble trying to find a specific object. With all the examples on searching lists online I can't seem to be able to get it.

I ask the user to input a number into int values checkId and checkUserId and then compare it. If it matches it should print out the title.

Iterator < Post > iter = posts.iterator();
while (iter.hasNext()) {
  if (Objects.equals(iter.next().getUserId(), checkUserId)) {
    System.out.println("found UserId");

    if (Objects.equals(iter.next().getId(), checkId)) {
      System.out.println("found Id");
      //prints the title of object
    }
  }
}

I then tried to use a stream:

List<Post> result = posts.stream()
        .filter(title -> checkId.equals(getId()))
        .findAny()
        .orElse(null);

All the code I cloned it from Java 11 HttpClient Tutorial by Dan Vega.


Solution

  • Your first attempt does not work because you are advancing the iterator twice on each iteration by calling next. Instead, store the result of Iterator#next and use it.

    Iterator<Post> iter = posts.iterator();
     while(iter.hasNext()){
            Post post = iter.next();
            if(Objects.equals(post.getUserId(), checkUserId)) {
                System.out.println("found UserId");
                System.out.println(post.getTitle());
            }
        }
    

    With streams:

    List<String> titles = posts.stream().filter(post-> checkId.equals(post.getId()))
                            .map(Post::getTitle).collect(Collectors.toList());
    titles.forEach(System.out::println);