[REST API] 3. Stream 실습

문정준's avatar
May 01, 2025
[REST API] 3. Stream 실습
 
package ex02; import lombok.Data; import java.util.Arrays; import java.util.Comparator; import java.util.stream.Collectors; public class StEx01 { public static void main(String[] args) { var list = Arrays.asList(1, 2, 3, 4, 5); Cart c1 = new Cart(1, "바나나", 1000); Cart c2 = new Cart(2, "바나나", 1000); Cart c3 = new Cart(3, "딸기", 2000); Cart c4 = new Cart(4, "사과", 3000); var cartList = Arrays.asList(c1, c2, c3, c4); // 1. map(가공) var new11 = list.stream().map(i -> i * 2).toList(); System.out.println(new11); var new12 = list.stream() .map(i -> i * 2) .filter(i -> i != 10) .toList(); System.out.println(new12); // 2. filter(검색, 삭제) var new21 = list.stream() .filter(i -> i < 3) .toList(); System.out.println(new21); // 3. count(개수), sorted(정렬), distinct(중복 제거) var new31 = list.stream() .sorted(Comparator.reverseOrder()) .map(i -> i / 3) .distinct() .count(); System.out.println(new31); // 4. mapToInt, sum, min, max, average var new41 = cartList.stream() // 1. 물가에 던져진 카트 4개 .mapToInt(cart -> cart.getPrice()) // 2. 물가에 던져진 int 4개 .min(); System.out.println(new41); // 5. group by // [key=[c1, c2], key=[c3], key=[c4]] var new51 = cartList.stream() .collect(Collectors.groupingBy(cart -> cart.getName())) .entrySet() .stream() .map(en -> en.getValue()) .toList(); System.out.println(new51); } @Data static class Cart { private int id; private String name; private int price; public Cart(int id, String name, int price) { this.id = id; this.name = name; this.price = price; } } }
notion image
 

Stream : 컬렉션을 가공하기 위해 임시로 올려두는 공간

  • map : 컬렉션 내의 요소들을 가공하여 다시 담음
  • filter : 컬렉션 내의 요소들을 검색, 조건에 맞지 않는 값 삭제
  • count : 컬렉션 내의 요소의 개수
  • sorted : 컬렉션 내의 요소 정렬
  • distinct : 컬렉션 내의 중복 요소 제거
  • mapToInt : 컬렉션 내의 요소를 꺼내서 정수로 다시 저장
    • max, min, sum, average 등 계산 함수 사용 가능
  • max : int 중 최댓값 저장
  • min : int 중 최솟값 저장
  • sum : int 요소들의 합 저장
  • average : int 요소들의 평균 저장
  • group by : 컬렉션 내의 요소들을 특정 key로 모아서 그룹핑
    • 다중 오브젝트 구현이 편리
 
notion image
 
notion image
Share article

sxias