본문 바로가기

업무관련/Java

JAVA - Stream 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * plantCd별로 그루핑하여 수량 합계 구함
 */
List<ProductionStatusDTO> plantList =
    searchList.stream()
        .collect(Collectors.groupingBy(foo -> foo.getPlantCd()))
        .entrySet()
        .stream()
        .map(e -> e.getValue().stream()
            .reduce((f1,f2) -> {
                BigDecimal multiplicand = new BigDecimal("100.0");
                String plantCd = f1.getPlantCd();
                String plantNm = "S".equals(plantCd) ? "서울" : "경기";
                BigDecimal mTotQty = f1.getmTotQty().add(f2.getmTotQty());
                BigDecimal mBadQty = f1.getmBadQty().add(f2.getmBadQty());
                BigDecimal mBadPer = (BigDecimal.ZERO.compareTo(f1.getmTotQty()) == 0) ? BigDecimal.ZERO : f1.getmBadQty().divide(f1.getmTotQty(), 2, BigDecimal.ROUND_HALF_UP).multiply(multiplicand);
                BigDecimal mTotKg = f1.getmTotKg().setScale(0, BigDecimal.ROUND_HALF_EVEN).add(f2.getmTotKg().setScale(0, BigDecimal.ROUND_HALF_EVEN));
                BigDecimal dGoodQty = f1.getdGoodQty().add(f2.getdGoodQty());
                BigDecimal dBadQty = f1.getdBadQty().add(f2.getdBadQty());
                BigDecimal dGoodKg = f1.getdGoodKg().setScale(0, BigDecimal.ROUND_HALF_EVEN).add(f2.getdGoodKg().setScale(0, BigDecimal.ROUND_HALF_EVEN));
                BigDecimal dBadPer = (BigDecimal.ZERO.compareTo(f1.getdGoodQty()) == 0) ? BigDecimal.ZERO : f1.getdBadQty().divide(f1.getdGoodQty(), 2, BigDecimal.ROUND_HALF_UP).multiply(multiplicand);
                return new ProductionStatusDTO(plantCd, plantNm, "", mTotQty, mBadQty, mBadPer, mTotKg, dGoodQty, dBadQty, dGoodKg, dBadPer);
            }))
            .map(f -> f.get())
            .collect(Collectors.toList());
cs

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
 * plantCd별로 제품수량 합계
 */
List<ProductionStatusDTO> sum =
        searchList.stream()
        .collect(Collectors.groupingBy(
                    ProductionStatusDTO::getPlantCd,
                    Collectors.reducing(
                        BigDecimal.ZERO,
                        ProductionStatusDTO::getdGoodQty,
                        BigDecimal::add
                    )
                ))
            .entrySet()
            .stream()
            .map(e2 -> new ProductionStatusDTO(e2.getKey(), e2.getValue()))
            .collect(Collectors.toList());
cs