2017-12-25 20 views
3

나는 다음과 같은 두 물체가Java Streams에서 추가 값을 처리하는 방법은 무엇입니까?

Product  ProductInventory 
-type   -Product 
-price  -quantity 
       -country 

내가 ProductInventory의 목록을 반복하여 저렴한을 찾을 필요가있다. 단계는 다음과 같습니다.

  1. product.type == input_type 경우와 quantity > input_quantity 다음 분에서 최대로 totalPrice에 의해 totalPrice = totalPrice + input_tax
  2. 정렬 기록
  3. 남아 새로운 객체 (국가, 수량에 첫 번째 레코드 &지도를 얻을 country != input_country 경우
  4. totalPrice = product.price * input_quantity
  5. , 총 가격)

총 가격을 생성해야하는 2 단계는 어떻게 처리 할 수 ​​있습니까? &을 스트림에서이 필드를 사용하는 방법은 무엇입니까?

+0

당신은'totalPrice' 값을 어디서나 저장할 수 없습니다. 왜 그 값을'ProductInventory'에 추가하지 않으시겠습니까? –

+0

래퍼 클래스를 사용하셨습니까? 또는 인벤토리 클래스에 직접 삽입 되었습니까? –

+1

productInventory가 다른 목적을 가지고 있기 때문에 래퍼 클래스에 삽입하려고합니다. – user1298426

답변

2

totalPrice 필드가 ProductInventory으로 선언 된 경우 다음을 수행 할 수 있습니다.

public class Product { 

    String type; 
    Integer price; 

    // getters, setters, constructors 
} 

public class Inventory { 

    Product product; 
    String country; 
    Integer quantity; 
    Integer totalPrice; 

    // getters, setters, and constructors 
} 

결과 값이 어느 쪽 Optional.empty(), 또는 당신이 최종 엔터티 형식으로 결과 값이있을 것이다, 나는 마지막 map to new object (country, quantity remaining, total price)을 생략

private Optional<FinalEntity> doLogic(String inputCountry, String inputType, Integer inputQuantity, Integer inputTax) { 
    return Stream.of(new Inventory(new Product("cola", 15), "germany", 1000)) 
      .filter(inv -> inv.getProduct().getType().equals(inputType) && inv.getQuantity() > inputQuantity) 
      .peek(inv -> { 
       Integer tax = inv.getCountry().equals(inputCountry) ? 0 : inputTax; 
       inv.setTotalPrice((inv.getProduct().getPrice() * inputQuantity) + tax); 
      }) 
      .sorted(Comparator.comparing(Inventory::getTotalPrice)) 
      .findFirst() 
      .map(Util::mapToFinalEntity); 
} 

이있는 인 그 시점에서 간단한 단계.

이 필드를 Inventory에 넣고 싶지 않은 경우 totalPrice을 포함하는 래퍼 클래스를 만들고 스트림 시작 부분의 인벤토리에 매핑 할 수 있습니다.

+0

인위적인'peek'보다는'map'을 쓰지 않는 이유는 무엇입니까? – apophis

+0

@apophis지도를 사용하는 것이 가능합니다. 중복 된 키가있을 수 있다고 생각하면 이러한 경우를 고려해야합니다. 질문은 totalPrice 값에 대해 람다 솔루션을 사용하여 단일 스트림을 가져 오도록 요청하는 것이 었습니다. 제 대답은 바로 그 것입니다. –

+0

'Stream '에있는 객체가 변형 된 경우'peek'을 사용하는 @apophis는 ** 필수 **입니다. 이 경우'map '을 사용하면 메소드의 계약이 깨지고 UB가됩니다. –