背景
(需求经过修改过)判断一个profile是否包含PROFILE-IN-A和PROFILE-IN-B且都是Enable=1打勾的.
既然已经JDK8了,那就用lambda
吧,如果是foreach可能比较难处理,用stream
的filter
则可以这样做.
核心代码可以这么写
int intCheck = profileServiceDtoList.stream().filter(e ->
"1".equals(e.getEnable())
&&(("PROFILE-IN-MOSHOW".equals(e.getServiceIdentifier()))||("PROFILE-IN-ADC".equals(e.getServiceIdentifier())))
).collect(Collectors.toList()).size();
代码SHOW
- 新建三个不同类型的profile,其中两个是要判断的,一个是
干扰
的. - 通过
steam
进行filter
,找出是否包含这两个元素(相当于把要判断的元素过滤进去) - 判断list的
size
大小(intCheck>1找到两个则代表同时出现)
public static void main(String[] args) {
List<ProfileServiceDto> profileServiceDtoList= new ArrayList<>(3);
ProfileServiceDto profileService1 = new ProfileServiceDto();
profileService1.setServiceId(1001L);
profileService1.setServiceIdentifier("PROFILE-IN-MOSHOW");
profileService1.setEnable("1");
profileServiceDtoList.add(profileService1);
ProfileServiceDto profileService2 = new ProfileServiceDto();
profileService2.setServiceId(1002L);
profileService2.setServiceIdentifier("PROFILE-IN-ADC");
profileService2.setEnable("1");
profileServiceDtoList.add(profileService2);
ProfileServiceDto profileService3 = new ProfileServiceDto();
profileService3.setServiceId(1003L);
profileService3.setServiceIdentifier("PROFILE-XXX-ABC");
profileService3.setEnable("1");
profileServiceDtoList.add(profileService3);
int intCheck = profileServiceDtoList.stream().filter(e ->
"1".equals(e.getEnable())&&(("PROFILE-IN-MOSHOW".equals(e.getServiceIdentifier()))||("PROFILE-IN-ADC".equals(e.getServiceIdentifier())))
).collect(Collectors.toList()).size();
System.out.println("intCheck->"+intCheck);
if(intCheck>1){
System.error.println("In one profile, cannot contain two more PROFILE-IN profile.");
}
}
转载:https://blog.csdn.net/moshowgame/article/details/102318343
查看评论