Programming

목록을 변환하는 방법

procodes 2020. 6. 3. 23:07
반응형

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


이 질문에는 이미 답변이 있습니다.

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

자바 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의 결합 / 연결분할 기능 :

하려면 CONCAT / 참여 와 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);

하려면 분할 로 ArrayList를 할 문자열의 모든 요소를 쉼표 ( " , ").

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

Done


I am having ArrayList of String, which I need to convert to comma separated list, without space. The ArrayList toString() method adds square brackets, comma and space. I tried the Regular Expression method as under.

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"

Please comment for more better efficient logic. ( The code is for Android / Java )

Thankx.


Java 8 solution if it's not a collection of strings:

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

You can use below code if object has attibutes under it.

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

If you're using Eclipse Collections (formerly GS Collections), you can use the makeString() method.

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

If you can convert your ArrayList to a FastList, you can get rid of the adapter.

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

Note: I am a committer for Eclipse collections.


Here is code given below to convert a List into a comma separated string without iterating List explicitly for that you have to make a list and add item in it than convert it into a comma separated string

Output of this code will be: Veeru,Nikhil,Ashish,Paritosh

instead of output of list [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

반응형