![[Springboot RestAPI] 3. Stream 활용 예제: 데이터 변환 및 집계 처리](https://image.inblog.dev?url=https%3A%2F%2Finblog.ai%2Fapi%2Fog%3Ftitle%3D%255BSpringboot%2520RestAPI%255D%25203.%2520Stream%2520%25ED%2599%259C%25EC%259A%25A9%2520%25EC%2598%2588%25EC%25A0%259C%253A%2520%25EB%258D%25B0%25EC%259D%25B4%25ED%2584%25B0%2520%25EB%25B3%2580%25ED%2599%2598%2520%25EB%25B0%258F%2520%25EC%25A7%2591%25EA%25B3%2584%2520%25EC%25B2%2598%25EB%25A6%25AC%26logoUrl%3Dhttps%253A%252F%252Finblog.ai%252Finblog_logo.png%26blogTitle%3Dsson17&w=2048&q=75)
📝 설명
Stream
은 컬렉션 데이터에 대해 선언적 방식으로 작업을 처리할 수 있도록 해주는 API입니다. 위 예제에서는 Stream
을 사용하여 데이터를 변환(map
), 필터링(filter
), 집계(count
, max
, sum
), 그룹화(groupingBy
) 등의 작업을 수행합니다.- map: 데이터를 변환하거나 가공합니다.
- filter: 조건에 맞는 데이터만 선택합니다.
- groupingBy: 데이터를 특정 조건을 기준으로 그룹화합니다.
- count, sum, max: 집계 작업을 수행하여 결과를 계산합니다.
📌 주요 작업
- map - 데이터를 변환:
var new11 = list.stream().map(i -> i * 2).toList();
map
을 사용하여 리스트의 각 원소에 2를 곱한 새로운 리스트를 생성합니다.- filter - 조건에 맞는 데이터 선택:
var new21 = list.stream().filter(i -> i < 3).toList();
filter
를 사용하여 3보다 작은 값만 필터링합니다.- count, sorted, distinct:
var new31 = list.stream().sorted(Comparator.reverseOrder())
.map(i -> i / 3)
.distinct()
.count();
리스트를 내림차순으로 정렬하고, 중복을 제거한 뒤, 나누기 연산 후 개수를 셉니다.
- mapToInt, sum, max, average:
var new41 = cartList.stream().mapToInt(cart -> cart.getPrice()).max();
mapToInt
를 사용하여 Cart
객체의 가격만 추출하고, max
를 통해 가장 큰 가격을 찾습니다.- groupingBy - 그룹화:
var new51 = cartList.stream()
.collect(Collectors.groupingBy(Cart::getName))
.entrySet()
.stream()
.map(en -> en.getValue())
.toList();
groupingBy
를 사용하여 Cart
객체들을 이름(name) 기준으로 그룹화하고 결과를 리스트로 반환합니다.💬 예시 코드
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()
.mapToInt(cart -> cart.getPrice())
.max();
System.out.println(new41);
//5. groupby [key=[c1, c2], key=[c3], key=[c4]]
var new51 = cartList.stream()
.collect(Collectors.groupingBy(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;
}
}
}
💡 활용 시나리오
- 데이터 가공:
map
을 사용하여 데이터의 형태를 변환하거나 계산할 수 있습니다.
- 필터링:
filter
를 사용하여 조건에 맞는 데이터만 추출하거나 불필요한 데이터를 제거할 수 있습니다.
- 그룹화:
groupingBy
를 활용하여 데이터를 특정 기준으로 그룹화하고, 각 그룹에 대한 처리를 쉽게 할 수 있습니다.
이와 같은
Stream
API는 컬렉션 데이터 처리에 있어서 가독성을 높이고, 불필요한 반복문을 제거하여 효율성을 극대화하는 데 유용합니다.📌 예시 JSON
{
"orderId": 1,
"products": [
{
"productId": 1,
"orderOptions": [
{"orderOptionId": 1, "orderOptionName": "파란바지", "orderQty": 2, "orderTotalPrice": 2000},
{"orderOptionId": 2, "orderOptionName": "빨간바지", "orderQty": 2, "orderTotalPrice": 4000}
]
},
{
"productId": 2,
"orderOptions": [
{"orderOptionId": 3, "orderOptionName": "하얀티", "orderQty": 5, "orderTotalPrice": 10000}
]
}
],
"sumPrice": 16000
}
🧑💻 변환 로직
List<OrderOption> or1Options = Arrays.asList(orOption1, orOption2, orOption3);
OrderDetailDTO orderDetailDTO = new OrderDetailDTO(or1Options);
String ex04 = gson.toJson(orderDetailDTO);
System.out.println(ex04);
이 코드는 주어진 데이터를
Stream
API를 통해 처리하여 요구된 결과를 출력하는 방식입니다.Share article