英文:
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="CountyID")
private County county;
}
Each County object also have an id, and i have a Collection list of HashSet containing all SchoolYear objects.
Collection<SchoolYear> schoolYears = new HashSet<>();
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 -> schoolYear.getCounyId() == newSchoolyear.getCountyId())
.findAny()
.isPresent();
if(isSchoolYearPresent){
//add to the collection
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论