Home > Software engineering >  How can I set a variable only when not null?
How can I set a variable only when not null?

Time:04-19

   @GetMapping("api/posts/{id}/comments")
public Result findComment(@PathVariable("id") Long id) {

    List<Comment> comments = commentRepository.findAllComment(id);
    System.out.println("parent: "   comments.get(2).getParent().getId());
    List<CommentDto> collect = comments.stream()
            .map(c -> new CommentDto(c))
            .collect(Collectors.toList());
    System.out.println("1. collect: "   collect);
    return new Result(collect.size(), collect);
}

@Data
static class CommentDto {
    private Long id;
    private Long commentId;
    private String comment;
    private String nickname;

    public CommentDto(Comment com) {
        id = com.getId();
        comment = com.getComment();
        if (!com.getParent().equals(null)) {
            commentId = com.getParent().getId();
        }
        nickname = com.getMember().getNickname();
    }
}

I am converting the values ​​received as a list into DTO one by one using "stream map". I want to set the "commentId" only when the converted values ​​are not null. What should I do? [enter image description here][1] [1]: https://i.stack.imgur.com/QtFVi.png

CodePudding user response:

You can do it like

public CommentDto(Comment com) {
        id = com.getId();
        comment = com.getComment();
        if (com.getParent() != null) {
            commentId = com.getParent().getId();
        }
        nickname = com.getMember().getNickname();
    }

or

public CommentDto(Comment com) {
        id = com.getId();
        comment = com.getComment();
        if (Objects.nonNull(com.getParent())) {
            commentId = com.getParent().getId();
        }
        nickname = com.getMember().getNickname();
    }
  • Related