programing

쉼표로 구분된 문자열을 목록으로 변환하는 방법

bestcode 2022. 7. 21. 00:36
반응형

쉼표로 구분된 문자열을 목록으로 변환하는 방법

콤마 구분 문자열을 일부 컨테이너(어레이, 리스트, 벡터 등)로 변환할 수 있는 임베디드 메서드가 Java에 있습니까?아니면 커스텀 코드를 작성해야 하나요?

String commaSeparated = "item1 , item2 , item3";
List<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그러면 단어가 목록에 배치되고 단어와 쉼표 사이의 공백이 축소됩니다.


어레이의 래퍼만 반환되는 것에 주의해 주십시오.예를 들어, 할 수 없습니다..remove()그 결과로부터List실제의 경우ArrayList더 사용해야 합니다.new ArrayList<String>.

Arrays.asList고정 크기를 반환합니다.List어레이에 의해 백업됩니다.일반적인 변형을 원한다면java.util.ArrayList다음 작업을 수행해야 합니다.

List<String> list = new ArrayList<String>(Arrays.asList(string.split(" , ")));

또는 Guava를 사용하는 경우:

List<String> list = Lists.newArrayList(Splitter.on(" , ").split(string));

사용방법Splitter는 문자열을 분할하는 방법에 대한 유연성을 높여 결과 및 트리밍 결과에서 빈 문자열을 건너뛸 수 있는 기능을 제공합니다.그것은 또한 보다 덜 이상한 행동을 가지고 있다.String.split또한 regex로 분할할 필요가 없습니다(이것은 하나의 옵션입니다).

2단계:

  1. String [] items = commaSeparated.split("\\s*,\\s*");
  2. List<String> container = Arrays.asList(items);
List<String> items= Stream.of(commaSeparated.split(","))
     .map(String::trim)
     .collect(Collectors.toList());

만약 a가ListOP에 기재되어 있는 최종 목표입니다만, 이미 받아들여진 답변이 최단이고 최량입니다.그러나 Java 8 Streams를 사용하여 다른 대안을 제공하고 싶습니다. Java 8 Stream이 추가 처리를 위한 파이프라인의 일부라면 더 많은 이점을 얻을 수 있습니다.

.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실행.

이러한 코드 예제는 그 자체로는 (더 많은 입력을 제외하고) 많은 것을 추가하는 것 같지 않지만, String을 Longs 목록으로 변환하는 것에 대한답변의 예처럼 더 많은 것을 할 계획이라면 스트리밍 API는 연산을 차례로 파이프라인으로 할 수 있어 매우 강력합니다.

완전성을 위해서요

다음은 CSV를 ArrayList로 변환하기 위한 다른 예입니다.

String str="string,with,comma";
ArrayList aList= new ArrayList(Arrays.asList(str.split(",")));
for(int i=0;i<aList.size();i++)
{
    System.out.println(" -->"+aList.get(i));
}

인쇄하다

> -- > --
> 와 --
>복수

List<String> items = Arrays.asList(commaSeparated.split(","));

그게 너한테 효과가 있을 거야.

기본 제공 메서드는 없지만 split() 메서드를 사용할 수 있습니다.

String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = 
new  ArrayList<String>(Arrays.asList(commaSeparated.split(",")));

asList와 스플릿을 조합할 수 있습니다.

Arrays.asList(CommaSeparated.split("\\s*,\\s*"))

이 코드가 도움이 될 거야

String myStr = "item1,item2,item3";
List myList = Arrays.asList(myStr.split(","));

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]

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());

「 」를 한 예Collections.

import java.util.Collections;
 ...
String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = new ArrayList<>();
Collections.addAll(items, commaSeparated.split("\\s*,\\s*"));
 ...

.String.split(",")된 문자열을 array ArrayList를 사용합니다.Arrays.asList(array)

groovy에서는 tokenize(문자 토큰) 메서드를 사용할 수 있습니다.

list = str.tokenize(',')

스플리터 클래스를 사용하여 얻을 수 있는 것과 같은 결과입니다.

var list = Splitter.on(",").splitToList(YourStringVariable)

(코틀린으로 작성)

이 질문은 오래되어 여러 번 답변되었지만 다음 사례를 모두 관리할 수 있는 답변은 없습니다.

  • ""빈은 빈 에 매핑해야 .-> 빈 은 빈 목록에 합니다.
  • " a, b , c ">첫 요소와 하여 모든 .-> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >
  • ",,"빈.-> 빈 요소는 삭제해야 합니다.

이렇게 org.apache.commons.lang3.StringUtils(예: https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.11):

StringUtils.isBlank(commaSeparatedEmailList) ?
            Collections.emptyList() :
            Stream.of(StringUtils.split(commaSeparatedEmailList, ','))
                    .map(String::trim)
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList());

단순한 분할식을 사용하면 정규식을 사용하지 않기 때문에 성능이 더 높을 수 있다는 장점이 있습니다.commons-lang3도서관은 가볍고 매우 흔하다.

이 콤마를 을 전제로 즉, 「」는 「」, 「」는 「」, 「」는 「」, 「」는 「」, 「」, 「」는 「」, 「」, 「」는 「」, 「」, 「」는 「」, 「」, 「」, 「」에 해 주세요."a, 'b,c', d"이 됩니다.["a", "'b", "c'", "d"] ["a", "b,c", "d"]를 참조해 주세요.

Java 9는 List.of()를 도입했습니다.

String commaSeparated = "item1 , item2 , item3";
List<String> items = List.of(commaSeparated.split(" , "));
List commaseperated = new ArrayList();
String mylist = "item1 , item2 , item3";
mylist = Arrays.asList(myStr.trim().split(" , "));

// enter code here

목록에는 주로 미리 컴파일된 패턴을 사용합니다.또한 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();
List<String> items = Arrays.asList(s.split("[,\\s]+"));

Kotlin에서는 String 목록이 이와 같이 ArrayList로 문자열을 변환할 때 사용할 수 있는 경우 이 코드 행을 사용합니다.

var str= "item1, item2, item3, item4"
var itemsList = str.split(", ")

자바에서는 이렇게 할 수 있다.

String catalogue_id = "A, B, C";
List<String> catalogueIdList = Arrays.asList(catalogue_id.split(", [ ]*"));

다음과 같이 할 수 있습니다.

이렇게 하면 공백이 제거되고 공백에 대해 걱정할 필요가 없는 쉼표로 분할됩니다.

    String myString= "A, B, C, D";

    //Remove whitespace and split by comma 
    List<String> finalString= Arrays.asList(myString.split("\\s*,\\s*"));

    System.out.println(finalString);

문자열 -> 컬렉션 변환: (String -> String [] -> 컬렉션)

//         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 -> String [] 변환:

String[] strArr = str.split(",");

그리고 컬렉션 -> 컬렉션:

List<String> list = new LinkedList<>(col);

Java 8에서 컬렉션을 쉼표로 구분된 문자열로 변환

list Of String 개체에는 ["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(",");

언급URL : https://stackoverflow.com/questions/7488643/how-to-convert-comma-separated-string-to-list

반응형