如果对此代码序列满足条件(条件:如果principal.isAdministrator()),我想对用户应用/不进行过滤。
for (User oneUser : subcontractorUserRole.getUsers()
.filter(new OTMFilter(Identity.CompanyEmployeeRel.class, selectedCounty.getSubcontractor()))
.filter(Identity.DELETED, false))
users.add(new GenericItem(oneUser.getId(), oneUser.getName()));
我想做这样的事情:
if ( principal.isAdministrator() {
for ( User oneUser : subcontractorUserRole.getUsers()
//.filter(new OTMFilter(Identity.CompanyEmployeeRel.class, selectedCounty.getSubcontractor()))
.filter(Identity.DELETED, false))
users.add(new GenericItem(oneUser.getId(), oneUser.getName()));
} else {
for ( User oneUser : subcontractorUserRole.getUsers()
.filter(new OTMFilter(Identity.CompanyEmployeeRel.class, selectedCounty.getSubcontractor()))
.filter(Identity.DELETED, false))
users.add(new GenericItem(oneUser.getId(), oneUser.getName()));
}
你知道一种优雅的方式来写这个没有重复的循环吗?我可以使用其他java 8 ...
谢谢。
答案 0 :(得分:0)
试试这个
subcontractorUserRole.getUsers()
.stream()
.filter(i -> principal.isAdministrador() || new OTMFilter(Identity.CompanyEmployeeRel.class, selectedCounty.getSubcontractor()))
.filter(Identity.DELETED, false)
.forEach(oneUser -> users.add(new GenericItem(oneUser.getId(), oneUser.getName())));
答案 1 :(得分:0)
如果您运行复杂逻辑,最好根据谓词进行流式传输。
Predicate<User> isAdmin = u -> principal.isAdministrator();
Predicate<User> isOTMFpositive = new OTMFilter(Identity.CompanyEmployeeRel.class, selectedCounty.getSubcontractor());
Predicate<User> notDeleted = ...
Predicate<User> fullPredicate = isAdmin.or(isOTMFpositive).and(notDeleted);
subcontractorUserRole.getUsers()
.stream()
.filter(fullPredicate)
.map(u -> new GenericItem(u.getId(), u.getName()))
.collect(collect(Collectors.toList()));