쉼표로 구분 된 문자열을 일부 컨테이너 (예 : 배열, 목록 또는 벡터)로 변환 할 수있는 내장 메소드가 Java에 있습니까? 아니면이를 위해 사용자 지정 코드를 작성해야합니까?
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = //method that converts above string into list??
쉼표로 구분 된 문자열을 일부 컨테이너 (예 : 배열, 목록 또는 벡터)로 변환 할 수있는 내장 메소드가 Java에 있습니까? 아니면이를 위해 사용자 지정 코드를 작성해야합니까?
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = //method that converts above string into list??
답변:
쉼표로 구분 된 문자열을 목록으로 변환
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
위의 코드는 다음과 같이 정의 된 구분 기호로 문자열을 분할합니다. 이렇게 zero or more whitespace, a literal comma, zero or more whitespace하면 단어가 목록에 배치되고 단어와 쉼표 사이의 공백이 축소됩니다.
유의하시기 바랍니다 단순히이 반환 배열에 래퍼 : 당신 CAN NOT 예를 들어 .remove()결과에서 List. 실제로 ArrayList는 추가로 사용해야 new ArrayList<String>합니다.
\s공백이 있으면 *일치는 0 번 이상 일치합니다. 따라서 \s*"공백을 0 번 이상 일치"를 의미합니다. 쉼표 앞뒤로 이것을 찾습니다. 따라서, 분할과 같은 문자열을 작동 "item1 , item2 , item3", 또는 "item1,item2 ,item3"당신이 얻을 수 있도록, 등 자바, 당신은 문자열에서 백 슬래시를 이스케이프 할 필요가\\s*
"[\\s,]+"값의 공백을 자르는 데 사용 하는 것이 좋습니다 . 예를 들어 " item1 , item2 , item3 , "됩니다 ["item1", "item2", "item3"].
"[\\s,]+"또한 쉼표로 구분 된 토큰 내에서 내부 공간으로 분할됩니다. 쉼표와 주변 공백을 사용하는 대신 쉼표가없는 경우에도 공백을 구분 기호로 처리합니다. "\\s*(,\\s*)+"쉼표로 구분 된 토큰 주위에서만 공백을 자르고 공백이거나 비어있는 문자열도 무시합니다.
Arrays.asList 고정 크기를 반환 List배열이 지원 . 정상적인 변경 가능을 원하면 java.util.ArrayList다음을 수행해야합니다.
List<String> list = new ArrayList<String>(Arrays.asList(string.split(" , ")));
또는 구아바를 :
List<String> list = Lists.newArrayList(Splitter.on(" , ").split(string));
를 사용 Splitter하면 문자열을 분할하는 방법에 더 많은 유연성을 제공하고 예를 들어 결과에서 빈 문자열을 건너 뛰고 결과를자를 수 있습니다. 또한 String.split정규 표현식으로 나눌 필요 가없는 것보다 이상한 행동이 적습니다 (단 하나의 옵션 일뿐입니다).
Arrays.asList기본 배열 주위에 래퍼를 제공 하지만 (요소 복사를 피함), new ArrayList(...)요소별로 복사를 수행 한다는 것입니다. 구문 분석 된 요소를 원하는 대상 컬렉션에 직접 추가 할 수있는 접근 방식을 선호해야합니다.
두 단계 :
String [] items = commaSeparated.split("\\s*,\\s*");List<String> container = Arrays.asList(items);split는 RegEx로 해석됩니다.
ListOP가 언급 한대로 a 가 최종 목표 인 경우 , 이미 승인 된 답변이 여전히 가장 짧고 가장 좋습니다. 그러나 Java 8 Streams를 사용하는 대안을 제공하고 싶습니다 . 추가 처리를위한 파이프 라인의 일부인 경우 더 많은 이점을 제공합니다.
.split 함수 (기본 배열)의 결과를 스트림에 래핑 한 다음 목록으로 변환합니다.
List<String> list =
Stream.of("a,b,c".split(","))
.collect(Collectors.toList());
ArrayListOP의 제목에 따라 결과를 저장 해야하는 경우 다른 Collector방법을 사용할 수 있습니다 .
ArrayList<String> list =
Stream.of("a,b,c".split(","))
.collect(Collectors.toCollection(ArrayList<String>::new));
또는 RegEx 구문 분석 API를 사용하여 :
ArrayList<String> list =
Pattern.compile(",")
.splitAsStream("a,b,c")
.collect(Collectors.toCollection(ArrayList<String>::new));
list변수 List<String>대신을 입력 한 상태로 두는 것도 고려할 수 있습니다 ArrayList<String>. 에 대한 일반적인 인터페이스는 List여전히 ArrayList구현 과 충분히 유사합니다 .
이 코드 예제 자체는 많은 것을 추가하지 않는 것 같습니다 (더 많은 타이핑 제외) . 문자열을 Longs List로 변환하는 것에 대한이 답변 과 같이 더 많은 것을 계획하고 있다면 스트리밍 API는 실제로 강력합니다. 작업을 차례로 파이프 라인
완전성을 위해 알다시피
List<String> items= Stream.of(commaSeparated.split(","))
.map(String::trim)
.collect(toList());
collect(toList())에collect(Collectors.toList()
collect(toList())정적 가져 오기를 사용하고 있습니다 Collectors.toList():)
Guava를 사용하여 문자열을 분할하고 ArrayList로 변환 할 수 있습니다. 이것은 빈 문자열에서도 작동하며 빈 목록을 반환합니다.
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
String commaSeparated = "item1 , item2 , item3";
// Split string into list, trimming each item and removing empty items
ArrayList<String> list = Lists.newArrayList(Splitter.on(',').trimResults().omitEmptyStrings().splitToList(commaSeparated));
System.out.println(list);
list.add("another item");
System.out.println(list);
다음을 출력합니다.
[item1, item2, item3]
[item1, item2, item3, another item]
를 사용하는 예 Collections입니다.
import java.util.Collections;
...
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = new ArrayList<>();
Collections.addAll(items, commaSeparated.split("\\s*,\\s*"));
...
Java 8 에서 스트림을 사용하여이를 해결하는 방법은 여러 가지가 있지만 IMO는 다음과 같은 하나의 라이너가 간단합니다.
String commaSeparated = "item1 , item2 , item3";
List<String> result1 = Arrays.stream(commaSeparated.split(" , "))
.collect(Collectors.toList());
List<String> result2 = Stream.of(commaSeparated.split(" , "))
.collect(Collectors.toList());
Splitter 클래스를 사용하여 동일한 결과를 얻을 수 있습니다.
var list = Splitter.on(",").splitToList(YourStringVariable)
(kotlin으로 작성)
나는 일반적으로 목록에 미리 컴파일 된 패턴을 사용합니다. 또한 이것은 listToString 표현식 중 일부를 따르는 대괄호를 고려할 수 있기 때문에 약간 더 보편적입니다.
private static final Pattern listAsString = Pattern.compile("^\\[?([^\\[\\]]*)\\]?$");
private List<String> getList(String value) {
Matcher matcher = listAsString.matcher((String) value);
if (matcher.matches()) {
String[] split = matcher.group(matcher.groupCount()).split("\\s*,\\s*");
return new ArrayList<>(Arrays.asList(split));
}
return Collections.emptyList();
Kotlin에서 문자열 목록이 이와 같고 문자열을 ArrayList로 변환하는 데 사용할 수있는 경우이 코드 줄을 사용하십시오
var str= "item1, item2, item3, item4"
var itemsList = str.split(", ")
List<String> items = Arrays.asList(s.split("[,\\s]+"));
문자열-> 콜렉션 변환 : (문자열-> 문자열 []-> 콜렉션)
// java version 8
String str = "aa,bb,cc,dd,aa,ss,bb,ee,aa,zz,dd,ff,hh";
// Collection,
// Set , List,
// HashSet , ArrayList ...
// (____________________________)
// || ||
// \/ \/
Collection<String> col = new HashSet<>(Stream.of(str.split(",")).collect(Collectors.toList()));
콜렉션-> 문자열 [] 변환 :
String[] se = col.toArray(new String[col.size()]);
문자열-> 문자열 [] 변환 :
String[] strArr = str.split(",");
그리고 수집-> 수집 :
List<String> list = new LinkedList<>(col);
Java 8 에서 쉼표로 구분하여 Collection을 문자열로 변환
listOfString 객체에는 [ "A", "B", "C", "D"] 요소가 포함됩니다.
listOfString.stream().map(ele->"'"+ele+"'").collect(Collectors.joining(","))
출력은 :- 'A', 'B', 'C', 'D'
Java 8에서 문자열 배열을 목록으로 변환
String string[] ={"A","B","C","D"};
List<String> listOfString = Stream.of(string).collect(Collectors.toList());
ArrayList<HashMap<String, String>> mListmain = new ArrayList<HashMap<String, String>>();
String marray[]= mListmain.split(",");
ArrayList있습니까? 질문을 읽었습니까?
ArrayList. 편집 내용을 첫 번째 개정판으로 롤백하고 (볼 수 있음) 첫 번째 개정판의 형식을 개선했습니다.