본문 바로가기

it-day/springboot

StringBuilder로 반복하여 콤마 표시

String test = null;

StringBuilder sb = new StringBuilder();

for (testDto dataMap : testDataList) {
    if (sb.length() > 0) {
        sb.append(",");
    }
    sb.append(dataMap.getTest_id());
}
test = sb.toString();

 

  1. String 변수 test를 null로 초기화
  2. StringBuilder를 초기화합니다.
  3. testDto 객체 리스트인 testDataList를 반복문으로 순회
  4. StringBuilder에 이미 내용이 있는지 확인하고, 있다면 콤마를 추가
  5. 현재 testDto 객체의 test_id를 StringBuilder에 추가
  6. 반복문이 끝난 후, StringBuilder의 내용을 문자열로 변환하여 test에 할당
  7. 이 과정을 통해 test 변수에는 콤마로 구분된 testDataList의 모든 test_id가 포함된 하나의 문자열이 저장