2017-12-01 5 views
0

ArrayList 개의 제품이 이미 초기화되었습니다. Product 생성자이다객체 속성으로 계산하도록 ArrayList 반복

public Product(String number, String type, double rentalDeposit, double rentalPrice, double lateFee, double buyPrice, int maxDuration) 

type을 열거하여 결정

protected enum productType {Basket, BabySeat, Helmet, Headlight, Bell}; 

난 열거 대한 toString 방법을 사용하여 전달 type. 나는 등, 내가 가진 (shop.getInventory()에 의해 주어진)를 ArrayList<Product>을 반복하고 typeBasket, BabySeat, Helmet의 얼마나 많은 즉, 거기에 각 type의 얼마나 많은 계산이 필요

Product 클래스는 getType() 방법이있다 문자열을 반환합니다.

for (Product.productType product : Product.productType.values()) { 
    int occurences = Collections.frequency(shop.getInventory(), product.toString()); 
} 

나는 Collections.frequency를 사용하여 시도했다, 그러나 그것은 0를 반환 유지하고 나는 이유를 모르겠어요.

if 문장을 사용하지 않고 반복하고이 금액을 찾는 다른 방법이 있습니까?

+0

'shop.getInventory()'를 다음과 같이 바꾸어보십시오. shop.getInventory(). stream(). map (제품 -> product.productType') .collect (Collectors.toList())'(get for-loop 제거 - 필요하지 않음). – alfasin

답변

0

shop.getInventory() 유형은 Collection<Product>입니다. .equals(Product)이 제품의 내부 유형 또는보다 간단하게 shop.getInventory().stream().filter(item -> product.toString().equals(item.getType())).count()에 대해 동등성을 검사하도록 제품을 정의 할 수 있습니다. (item.getType()을 대체하지만 Product에서 유형 필드를 추출합니다 (예 : item.type 등).

0

일부 조건에 해당하는 목록의 항목을 계산하는 간단한 방법은 Collectors.groupingByCollectors.counting을 사용하는 것입니다. 다음과 같은 뭔가 :

Map<ProductType,Long> counts = products.stream() 
    .collect(groupingBy(Product::getType, counting())); 

이 문은 제품의 스트림으로 목록을 켭니다 '로 읽을 수 스트림에 익숙하지 않은 경우, 제품 별 제품은 다음 입력 그룹을 생성하면 각 그룹을 계산 유형에서 수에 이르는지도. '