자바 스트림을 사용하여 기존의getProducts 메서드를 리팩토링 하겠습니다. 스트림 API는 컬렉션을 처리하는 간결하고 읽기 쉬운 방법을 제공합니다.
public List<ProductResponseDto> getProducts() {
List<Product> productList = productRepository.findAll();
List<ProductResponseDto> responseDtoList = new ArrayList<>();
for (Product product : productList) {
responseDtoList.add(new ProductResponseDto(product));
}
return responseDtoList;
}
import java.util.List;
import java.util.stream.Collectors;
public List<ProductResponseDto> getProducts() {
return productRepository.findAll().stream()
.map(ProductResponseDto::new)
.collect(Collectors.toList());
}
productRepository.findAll().stream(): findAll() 메서드로 가져온 List<Product>를 스트림으로 변환합니다.map(ProductResponseDto::new): 각 Product 객체를 ProductResponseDto 객체로 매핑합니다.collect(Collectors.toList()): 매핑된 ProductResponseDto 객체들을 리스트로 수집합니다.이 방식은 코드가 더 간결하고 읽기 쉬우며, 스트림 API의 장점을 활용할 수 있습니다.