Stream

배고픈 징징이 ㅣ 2023. 1. 31. 15:58

1. Stream Method

  • map : 특정조건에 해당하는 값으로 변환
  • filter : 조건에 따라 걸러내는 작업
  • sorted : 정렬
    sorted() : 알파벳 순서대로, 역순은 sorted(Comparator.reverseOrder)
    sorted(Comparator.comparing(String::length)) : comparing 인자값으로 정렬

 

2. Stream Collectors

  • toList, toSet : 결과를 List나 Set으로 변경
  • toMap : 결과를 Map으로 변경
  • joining : 결과를 String으로 이어붙일때 사용
  • counting : 결과를 카운트할때 사용
  • groupingBy : 결과를 SQL의 GROUP BY 처럼 그룹핑할때 사용

 

// 1. Dto에 추가로 파라미터를 더 보내고 싶을때, 아래 Dto 참조
List map = response.stream()
    .map(e -> new BestParseDtoV2(e, isApp))
    .collect(Collectors.toList());
// 2. 다른 Dto로 바꾸고 싶을때
var map = response.stream()
    .map(BestParseDtoV2::new)
    .collect(Collectors.toList());

String filter = request.getKeywords().stream()
    .filter(e -> !StringUtils.isEmpty(e) && !e.trim().equals(""))
    .collect(Collectors.joining(" "));
    
List sorted = request.getKeywords().steram()
    .sorted()
    .collect(Collectors.toList());
@Getter
@Setter
@NoArgsConstructor
@ApiModel(description = "BEST 상품")
public class BestParseDtoV2 {
    @ApiModelProperty(value = "아이템 ID")
    private Long item_id;
    @ApiModelProperty(value = "상품명")
    private String item_name;   
    ...    
    public BestParseDtoV2(BestDtoV2 bestDtoV2, boolean isApp) {
        this.item_id = Long.valueOf(bestDtoV2.getItemid());
        this.item_name = bestDtoV2.getItemname();
        ...
        this.move_url = urlProvider.getItemDetailUrl(isApp, bestDtoV2.getItemid());
    }
}
반응형

'Java' 카테고리의 다른 글

Access Modifier ( 접근 지정자 )  (0) 2023.02.08
ThreadLocal  (0) 2023.02.07
@pathvariable  (0) 2023.01.26
VO 데이터 추출  (0) 2023.01.26
Ehcache3 & SpEL  (0) 2023.01.26