ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [코테준비] 백엔드 실무형 - json/conditionfiltering
    카테고리 없음 2025. 11. 22. 17:09

    쳇지피티활용

    파싱 

    ObjectMapper mapper = new ObjectMapper();
    List<Agent> list = mapper.readValue(input, new TypeReference<List<Agent>>() {});

    codility 에서는 임포트안되니까 

    dto생성자로 해결한다. 

     

    3번 문제 : 실무형 데이터 처리 패턴 

    3번 문제 특징은 아래 4단계로 요약돼:

    단계 1) 입력 = JSON / 배열 / Map 비슷한 구조

    예)

    [ {"agentId": "A1", "status": "DELIVERING", "distance": 12}, {"agentId": "A2", "status": "IDLE", "distance": 3} ]

    단계 2) 조건 필터링

    예)

    • status = IDLE 인 데이터만 필터링
    • distance < 10 인 데이터만 필터링
    • type = “DELIVERY” 인 데이터만 추출

    단계 3) Grouping / Aggregation

    • agentId 기준 데이터 묶기
    • type 기준 count
    • storeId 기준 sum

    단계 4) 정렬 & 최종 결과 반환

    조건에 따라

    • 거리 오름차순
    • 주문 수 많은 순
    • ID 사전순
      등 정렬 기준 존재.

    이 유형을 빠르게 풀기 위한 핵심 패턴 3개

    패턴 A: DTO 만들기 → 리스트로 파싱

    (JSON → DTO 객체 변환)

     
    class Agent { String agentId; String status; int distance; Agent(String agentId, String status, int distance) { this.agentId = agentId; this.status = status; this.distance = distance; } }

    그리고 본 문제에서는 보통 배열로 주어지므로 DTO 생성 반복

     
    List<Agent> list = new ArrayList<>(); for (int i = 0; i < agentIds.length; i++) { list.add(new Agent(agentIds[i], status[i], distance[i])); }

    실무형 문제 99%는 이렇게 객체 리스트로 만들어놓고 시작해야 코드 예뻐짐.


    패턴 B: 필터링

    Stream 또는 직접 반복문.

    ✔ Stream 예시

     
    List<Agent> filtered = list.stream() .filter(a -> a.status.equals("IDLE")) .filter(a -> a.distance < 10) .collect(Collectors.toList());

    ✔ 반복문 버전

     
    List<Agent> filtered = new ArrayList<>(); for (Agent a : list) { if (a.status.equals("IDLE") && a.distance < 10) { filtered.add(a); } }

    패턴 C: Grouping / Aggregation

    예) agentId 기준으로 몇 번 등장했는지 count

    ✔ groupBy 예시

     
    Map<String, Long> countByAgent = list.stream().collect(Collectors.groupingBy( a -> a.agentId, Collectors.counting() ));

    예) sum 구하기

     
    Map<String, Integer> distanceSum = list.stream().collect(Collectors.groupingBy( a -> a.agentId, Collectors.summingInt(a -> a.distance) ));

    패턴 D: 정렬

    조건 여러 개 정렬

     
    filtered.sort((a, b) -> { if (a.distance != b.distance) { return a.distance - b.distance; // 오름차순 } return a.agentId.compareTo(b.agentId); // 동일하면 ID순 });
     

    정렬 패턴 D — 최신 Java(Comparator 체인) 버전

    🔥 1) 기본 정렬 (distance → agentId)

     
    filtered.sort( Comparator.comparingInt((Agent a) -> a.distance) .thenComparing(a -> a.agentId) );

    ✔ 여기서의 포인트

    • comparingInt() → distance 오름차순
    • thenComparing() → 거리 같을 때 agentId 사전순
    • 빼기 연산 a.distance - b.distance처럼 오버플로우 위험 없음
    • 코드가 훨씬 읽기 쉽고 명확함

    🔥 2) distance 내림차순 → agentId 오름차순

     
    filtered.sort( Comparator.comparingInt((Agent a) -> a.distance).reversed() .thenComparing(a -> a.agentId) );

    🔥 3) agentId 오름차순 → distance 오름차순

     
    filtered.sort( Comparator.comparing((Agent a) -> a.agentId) .thenComparingInt(a -> a.distance) );

    🔥 4) 여러 조건 복잡한 정렬도 가능

    예) status 우선순위 → distance 오름차순 → agentId 오름차순

     
    filtered.sort( Comparator.comparing((Agent a) -> a.status) .thenComparingInt(a -> a.distance) .thenComparing(a -> a.agentId) );

    📌 정리: 3번 문제는 아래 순서로 풀면 무조건 90점+

    1. DTO 만들기
    2. 입력 배열 → DTO list 변환
    3. 조건대로 필터링
    4. grouping 필요하면 grouping
    5. 정렬 기준대로 정렬
    6. 결과값 반환 형태 만들기 (String[], int[], Map 등)

    이 흐름을 기계적으로 외우면 코테 점수 상승함.

Designed by Tistory.