>  기사  >  Java  >  Java에서 Stream을 사용하여 if에서 너무 많은 조건의 판단을 최적화하는 방법

Java에서 Stream을 사용하여 if에서 너무 많은 조건의 판단을 최적화하는 방법

王林
王林앞으로
2023-05-05 10:40:062282검색

Stream을 사용하여 if에서 판단 조건이 너무 많은 경우 최적화

Jdk1.8 새로운 기능 Stream 스트림에는 anyMatch, allMatch, noneMatch라는 세 가지 API가 있으며 각각의 기능은 다음과 같습니다. 조건 중 하나가 조건을 만족하면 true를 반환합니다.

  • allMatch: 모든 조건이 충족되면 true가 반환됩니다.

  • noneMatch: 모든 조건이 충족되지 않으면 true가 반환됩니다.

  • 실제로 사용되는 방식은 매우 간단합니다.

    List<String> list = Arrays.asList("a", "b", "c","d", "");
    //任意一个字符串判断不为空则为true
    boolean anyMatch = list.stream().anyMatch( s->StringUtils.isEmpty(s));
    //所有字符串判断都不为空则为true
    boolean allMatch = list.stream().allMatch( s->StringUtils.isEmpty(s));
    //没有一个字符判断为空则为true
    boolean noneMatch = list.stream().noneMatch( s->StringUtils.isEmpty(s));
  • 위의 세 가지 구현 방법에 따르면 if에 너무 많은 판단 조건이 있는 상황을 어느 정도 최적화할 수 있음을 알 수 있습니다. 어떤 시나리오에서 최적화를 사용하는 것이 더 적합합니까?

일상적인 실제 개발에서 우리는 다음과 같은 많은 판단 조건을 가진 코드를 본 적이 있을 것입니다:

 if(StringUtils.isEmpty(str1) || StringUtils.isEmpty(str2) ||
    StringUtils.isEmpty(str3) || StringUtils.isEmpty(str4) ||
    StringUtils.isEmpty(str5) || StringUtils.isEmpty(str6)
   ){
 .....
}

이때 최적화를 위해 스트림 흐름을 사용하는 것을 고려할 수 있습니다. 최적화된 코드는 다음과 같습니다:

if(Stream.of(str1, str2, str3, str4,str5,str6).anyMatch(s->StringUtils.isEmpty(s))){
 .....
 }

이렇게 최적화되었습니다. ifs 더미 속에 쌓인 조건들보다 더 우아하지 않나요?

물론 이는 또는 조건에만 해당됩니다. 및 조건이 발생하는 경우 Stream을 사용하여 최적화할 수도 있습니다. 예:

if(StringUtils.isEmpty(str1) && StringUtils.isEmpty(str2) &&
   StringUtils.isEmpty(str3) && StringUtils.isEmpty(str4) &&
   StringUtils.isEmpty(str5) && StringUtils.isEmpty(str6)
){
   .....
}

Stream을 사용하여 최적화한 후:

if(Stream.of(str1, str2, str3, str4,str5,str6).allMatch(s->StringUtils.isEmpty(s))){
  .....
}

위 내용은 Java에서 Stream을 사용하여 if에서 너무 많은 조건의 판단을 최적화하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제