programing

목록을 명시적으로 반복하지 않고 목록을 쉼표로 구분된 문자열로 변환하는 방법

prostudy 2022. 4. 17. 10:04
반응형

목록을 명시적으로 반복하지 않고 목록을 쉼표로 구분된 문자열로 변환하는 방법

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");

이제 나는 명시적으로 반복하지 않고 이 목록의 출력을 1,2,3,4로 원한다.

Android 사용 시:

android.text.TextUtils.join(",", ids);

Java 8의 경우:

String csv = String.join(",", ids);

Java 7-에는 더러운 방법이 있다(참고: 목록포함된 문자열을 삽입하지 않는 경우에만 작동한다). - 분명히,List#toString루프를 수행하여idList코드에는 표시되지 않음:

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
String idList = ids.toString();
String csv = idList.substring(1, idList.length() - 1).replace(", ", ",");
import com.google.common.base.Joiner;

Joiner.on(",").join(ids);

또는 StringUtils를 사용할 수 있음:

   public static String join(Object[] array,
                              char separator)

   public static String join(Iterable<?> iterator,
                              char separator)

제공된 배열/숫자의 요소를 제공된 요소 목록이 포함된 단일 문자열로 결합하십시오.

http://commons.apache.org/proper/commons-lang/javadocs/api-3.3.2/org/apache/commons/lang3/StringUtils.html

목록을 CSV 형식으로 변환하려면 .........

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");

// CSV format
String csv = ids.toString().replace("[", "").replace("]", "")
            .replace(", ", ",");

// CSV format surrounded by single quote 
// Useful for SQL IN QUERY

String csvWithQuote = ids.toString().replace("[", "'").replace("]", "'")
            .replace(", ", "','");

가장 빠른 방법은

StringUtils.join(ids, ",");

다음 사항:

String joinedString = ids.toString()

쉼표로 구분된 목록을 제공할 것이다.자세한 내용은 문서를 참조하십시오.

정사각형 괄호를 제거하기 위해 후처리를 해야 할 것이지만 너무 까다로운 것은 아니다.

단일 라이너(순수 Java)

list.toString().replace(", ", ",").replaceAll("[\\[.\\]]", "");

ArrayList에서 조인/연결 & 분할 기능:

배열 목록의 모든 요소쉼표(""), 문자열로 결합하려면

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
String allIds = TextUtils.join(",", ids);
Log.i("Result", allIds);

문자열의 모든 요소를 쉼표(",")가 있는 배열 목록으로 분할하려면

String allIds = "1,2,3,4";
String[] allIdsArray = TextUtils.split(allIds, ",");
ArrayList<String> idsList = new ArrayList<String>(Arrays.asList(allIdsArray));
for(String element : idsList){
    Log.i("Result", element);
}

공백 없이 쉼표로 구분된 목록으로 변환해야 하는 ArrayList of String이 있어.ArrayList toString() 메서드는 대괄호, 쉼표 및 공간을 추가한다.나는 아래와 같이 정규 표현 방식을 시도했다.

List<String> myProductList = new ArrayList<String>();
myProductList.add("sanjay");
myProductList.add("sameer");
myProductList.add("anand");
Log.d("TEST1", myProductList.toString());     // "[sanjay, sameer, anand]"
String patternString = myProductList.toString().replaceAll("[\\s\\[\\]]", "");
Log.d("TEST", patternString);                 // "sanjay,sameer,anand"

보다 효율적인 논리를 위해 의견을 제시하십시오. (코드는 Android/Java용임).

고마워

물체가 아래에 있는 경우 아래 코드를 사용할 수 있다.

String getCommonSeperatedString(List<ActionObject> actionObjects) {
    StringBuffer sb = new StringBuffer();
    for (ActionObject actionObject : actionObjects){
        sb.append(actionObject.Id).append(",");
    }
    sb.deleteCharAt(sb.lastIndexOf(","));
    return sb.toString();
}

Java 8 솔루션이 문자열 모음이 아닌 경우:

{Any collection}.stream()
    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
    .toString()

Eclipse Collections(이전의 GS Collections)를 사용하는 경우makeString()방법

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");

Assert.assertEquals("1,2,3,4", ListAdapter.adapt(ids).makeString(","));

변환할 수 있는 경우ArrayList완전히FastList어댑터를 제거할 수 있다.

Assert.assertEquals("1,2,3,4", FastList.newListWith(1, 2, 3, 4).makeString(","));

참고: 나는 Eclipse 컬렉션을 위한 커밋자 입니다.

다음은 목록을 쉼표로 구분된 문자열로 변환하기 위해 쉼표로 구분된 문자열로 변환하기 위해 쉼표로 구분된 문자열로 변환하기보다 목록을 만들고 해당 문자열에서 항목을 추가해야 함을 명시적으로 나타내는 코드 입니다.

이 코드의 출력은 Veeru, Nikhil, Ashish, Paritosh가 될 것이다.

목록 출력 대신 [베루, 니힐, 아시쉬, 파리토시]

String List_name;
List<String> myNameList = new ArrayList<String>();
myNameList.add("Veeru");
myNameList.add("Nikhil");
myNameList.add("Ashish");
myNameList.add("Paritosh");

List_name = myNameList.toString().replace("[", "")
                    .replace("]", "").replace(", ", ",");

참조URL: https://stackoverflow.com/questions/10850753/how-to-convert-a-liststring-into-a-comma-separated-string-without-iterating-li

반응형