2017-11-20 2 views
1

stream을 (를) 사용하여 firstName 및 lastName으로 친구를 찾으려고합니다. 이 스트림에서 객체를 반환 할 수 있습니까? 그 이름과 성을 가진 친구처럼? 지금은 반환이 일치하지 않기 때문입니다.스트림에서 객체 가져 오기

@Override 
public Friend findFriend(String firstName, String lastName) throws FriendNotFoundException { 
    if (firstName == null || lastName ==null) { 
     throw new IllegalArgumentException("There is no parameters"); 
    } 

      List<Friend> result = friends.stream() 
      .filter(x -> (firstName.equals(x.getFirstName())) && 
      (lastName.equals(x.getLastName())))) 
      .collect(Collectors.toList()); 

      return result; 
+2

'collect()'대신'findAny()'또는'findFirst()'를 호출하십시오. – shmosel

답변

2

과 같이 findFirst을 활용 :

return friends.stream() 
       .filter(x -> firstName.equals(x.getFirstName()) && 
          lastName.equals(x.getLastName()) 
        ) 
       .findFirst().orElse(null); 

또는 돌려 주어 Optional<Friend> 예 :

다음 무시하고있는 방법은 또한 Optional<Friend>을 반환 선언해야 함을 의미
@Override 
public Optional<Friend> findFriend(String firstName, String lastName) throws FriendNotFoundException { 
     if (firstName == null || lastName == null) { 
      throw new IllegalArgumentException("There is no parameters"); 
     } 

     return friends.stream() 
       .filter(x -> firstName.equals(x.getFirstName()) && 
          lastName.equals(x.getLastName()) 
        ) 
       .findFirst(); 
} 

및 필요한 경우 상속 계층 구조를 위로 올라간다.

+0

효과가 있습니다! 감사! – Donne

+0

선택적 힌트가있는 좋은 힌트. 그러나 findAny()를 사용하는 것이 좋습니다. 큰 스트림의 경우 더 효율적일 수 있습니다. –

+0

@MalteHartwig 사실,'findAny'는'findAny'를 사용하는 것이 아니라'findAny'를 사용하는 제약이 적기 때문에 parallelStream으로 대량 작업을 수행 할 때'findAny'를 추천합니다. –