如何使用对象内部的对象来过滤单个对象列表?

huangapple go评论63阅读模式
英文:

How to filter a single list with objects with object inside the object?

问题

我有一个类似这样的对象

public class SchoolYear {

    private static final long serialVersionUID = 1L;

    @BigInt
    private long schoolYearID;

    @ForeignKey(id="CountyID")
    private County county;
}

每个 County 对象也有一个 id而且我有一个包含所有 SchoolYear 对象的 HashSet 集合列表

Collection<SchoolYear> schoolYears = new HashSet<>();

我正在将每个 SchoolYear 对象添加到 schoolYears 列表中但是如果列表中已经有一个具有相同 CountyId 的 SchoolYear 对象我希望避免添加另一个 SchoolYear 对象因此我希望在添加到列表之前进行检查)。因此一个 SchoolYear 可能具有不同的属性但 CountyId 始终相同但我不希望有多个具有相同 CountyId 的 SchoolYear 对象怎么做呢

或者我可以使用 Java Streams 进行过滤吗但是如何操作呢

我希望我的解释足够清楚如果需要的话我可以提供更多信息

谢谢帮助
英文:

I have a object which looks like this:

public class SchoolYear {

    private static final long serialVersionUID = 1L;

    @BigInt
    private long schoolYearID;


    @ForeignKey(id=&quot;CountyID&quot;)
    private County county;
}

Each County object also have an id, and i have a Collection list of HashSet containing all SchoolYear objects.

Collection&lt;SchoolYear&gt; schoolYears = new HashSet&lt;&gt;();

I am adding each SchoolYear object into the schoolYears list. But I want to avoid adding a SchoolYear object if a SchoolYear object with an CountyId already in the list (so i want to check before adding to the list). So a SchoolYear can have different attributes, but CountyId always same, but i dont want multiple object of SchoolYear with same CountyId. How to do it?

Or can i filter by Java Streams? But how?

I hope my explanation is good, otherwise i can add more information if needed.

Thank you for the help!

答案1

得分: 0

boolean isSchoolYearPresent = schoolYears.stream()
    .filter(schoolYear -> schoolYear.getCountyId() == newSchoolyear.getCountyId())
    .findAny()
    .isPresent();
if (isSchoolYearPresent) {
    //add to the collection
}
英文:

Something along these lines.

boolean isSchoolYearPresent = schoolYears.stream()
    .filter(schoolYear -&gt; schoolYear.getCounyId() == newSchoolyear.getCountyId())
    .findAny()
    .isPresent();
if(isSchoolYearPresent){
    //add to the collection
}

huangapple
  • 本文由 发表于 2020年6月6日 01:01:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/62220559.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定