Java stream判斷列表是否包含某幾個元素/重複元素

Moshow鄭鍇發表於2020-04-07

Java stream判斷列表是否包含某幾個元素

(需求經過修改過)判斷一個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.");
	}
}

Java stream判斷列表是否包含重複元素

思路是通過一個distinct的list,然後跟原先的list來判斷大小,如果不一致(原先list.size>distinctList.size)則表示有重複元素

		//profileServiceDtoList路上,不累贅
		//多了一個profileService1.setGroupId("A");profileService1.setGroupId("B");profileService3.setGroupId("A");
		List<String> groupList = new ArrayList<>(4);
        profileServiceDtoList.stream().forEach(e -> {
            if ("Y".equals(e.getEnable()) && StringUtils.isNotEmpty(e.getGroupId())) {
                groupList.add(e.getGroupId());
            }
        });
        int distinctGroupSize = groupList.stream().distinct().collect(Collectors.toList()).size();
        if (groupList.size() > distinctGroupSize) {
            throw new ValidationException("100001","In one profile, the services with the same groupId cannot co-exist.");
        }

相關文章