Java8 null check collection before add element

时间:2016-08-31 12:25:10

标签: java-8

I have an entity. Some times the inner collection of info elements not get created. So to implementing correspond method I need null checking.

public class Tag {
    ...
    private Set<ProjectInfo> projectInfoSet;
    ...

    public void addProjectInfo(ProjectInfo projectInfo) {
    if (this.projectInfoSet == null) {
        this.projectInfoSet = new HashSet<>();
    }
    this.projectInfoSet.add(projectInfo);
    }
}

I believe Java8 provides better solution. For example using Optional class. But i'm not sure if it is good to use Optional in my entity class. Other case possible I do not need here optional, because I need to create projectInfoSet, it should like behavioral pattern strategy.

Can someone recommend the better implementation way or explanations how it could be done in better way.

2 个答案:

答案 0 :(得分:2)

如果您使用的是jackson,可以使用配置参数进行初始化吗?

喜欢这里

    ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_DEFAULT);

答案 1 :(得分:1)

Add initial value to your field and forget about null-check:

public class Tag {
    ...
    private Set<ProjectInfo> projectInfoSet = new HashSet<>();
    ...

    public void addProjectInfo(ProjectInfo projectInfo) {
        this.projectInfoSet.add(projectInfo);
    }
}
相关问题