小言_互联网的博客

Java stream判断列表是否包含某几个元素

393人阅读  评论(0)

背景

(需求经过修改过)判断一个profile是否包含PROFILE-IN-A和PROFILE-IN-B且都是Enable=1打勾的.

既然已经JDK8了,那就用lambda吧,如果是foreach可能比较难处理,用streamfilter则可以这样做.
核心代码可以这么写

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

  1. 新建三个不同类型的profile,其中两个是要判断的,一个是干扰的.
  2. 通过steam进行filter,找出是否包含这两个元素(相当于把要判断的元素过滤进去)
  3. 判断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
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场