List 안의 내용을 , 로 구분을 줘서 하나의 문자열로 연결하고 싶었다.
for문을 이용하여 하나씩 추가할 수도 있지만,
자바에서 제공하는 라이브러리 StringUtils에 간편한 메서드가 존재한다.
먼저 StringUtils 라이브러리를 추가해야 한다.
lib 폴더에 직접 넣을 경우
https://commons.apache.org/proper/commons-lang/download_lang.cgi
Lang – Download Apache Commons Lang
Download Apache Commons Lang Using a Mirror We recommend you use a mirror to download our release builds, but you must verify the integrity of the downloaded files using signatures downloaded from our main distribution directories. Recent releases (48 hour
commons.apache.org
pom.xml에 추가할 경우
https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.8
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
StringUtils.join(리스트, "구분자");
public static String join(final Iterable<?> iterable, final String separator) {
if (iterable == null) {
return null;
}
return join(iterable.iterator(), separator);
}
* StringUtils 는 파라미터 값이 null 이어도 NullPointException이 발생하지 않는다.
List<string> list = new ArrayList<string>();
list.add("test1");
list.add("test2");
list.add("test3");
list.add("test4");
String str = StringUtils.join(list, ",");
str은 "test1,test2,test3,test4" 와 같은 형태로 출력 된다.
'JAVA' 카테고리의 다른 글
| [JAVA] StreamAPI를 이용 한 List 값 중복 제거 (0) | 2023.06.22 |
|---|---|
| [JAVA] object List to map using stream - Object List를 Map 으로 변환하기 (0) | 2023.06.20 |
| [JAVA] Java Stream - 두 개의 List 객체 비교하기 (0) | 2023.06.15 |
| [JAVA] HashMap Key,Value 가져오기 (0) | 2023.04.17 |
| [JAVA] JSON Data to JAVA Class(Object) - Json 데이터 객체(VO)로 변환(파싱) (0) | 2023.04.17 |