자바 : 문자열 목록을 변환

자바 스크립트가 있습니다Array.join()

js>["Bill","Bob","Steve"].join(" and ")
Bill and Bob and Steve

자바는 이러한 일이있다? 나는 모두 StringBuilder 뭔가를 직접 구성 할 수 있습니다 알고 :

static public String join(List<String> list, String conjunction)
{
   StringBuilder sb = new StringBuilder();
   boolean first = true;
   for (String item : list)
   {
      if (first)
         first = false;
      else
         sb.append(conjunction);
      sb.append(item);
   }
   return sb.toString();
}

그런 일이 JDK의 일부가 될 경우 ...하지만, 그것은 그렇게 이해가되지 않습니다.


# 1 층

나는 (나는 콩 및 사용을 위해 사용 쓴 toString그렇게 쓰지 않는다 Collection<String>)

public static String join(Collection<?> col, String delim) {
    StringBuilder sb = new StringBuilder();
    Iterator<?> iter = col.iterator();
    if (iter.hasNext())
        sb.append(iter.next().toString());
    while (iter.hasNext()) {
        sb.append(delim);
        sb.append(iter.next().toString());
    }
    return sb.toString();
}

그러나, JSP가 지원되지 않는 Collection, 그래서 TLD에 대한, 내가 쓴 :

public static String join(List<?> list, String delim) {
    int len = list.size();
    if (len == 0)
        return "";
    StringBuilder sb = new StringBuilder(list.get(0).toString());
    for (int i = 1; i < len; i++) {
        sb.append(delim);
        sb.append(list.get(i).toString());
    }
    return sb.toString();
}

그리고 배치 .tld파일 :

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
    <function>
        <name>join</name>
        <function-class>com.core.util.ReportUtil</function-class>
        <function-signature>java.lang.String join(java.util.List, java.lang.String)</function-signature>
    </function>
</taglib>

JSP 파일 등의 기능에서 :

<%@taglib prefix="funnyFmt" uri="tag:com.core.util,2013:funnyFmt"%>
${funnyFmt:join(books, ", ")}

하우스 # 2

아니, 편리한 방법으로 이러한 표준 자바 API가 없습니다.

당연히, 당신은 아파치 코 몬즈, 직접 작성하지 않으려면 자신의 StringUtils에 클래스 것은 이 기능을 제공합니다.


하우스 # 3

당신은 StringUtils에 클래스를 가지고 방법을 결합 라이브러리 아파치 평민을 사용할 수 있습니다.

이 링크를 확인 HTTPS : //commons.apache.org/proper/commons-lang/javadocs/api.2.0/org/apache/commons/lang/StringUtils.html를

시간이 지남에 따라, 위의 링크는이 경우에, 당신은 당신이 최신 참고 자료를 찾을 수 있습니다 인터넷에서 "아파치 평민 StringUtils에"를 검색 할 수 있습니다, 오래된 될 수 있음을 유의하시기 바랍니다.

(스레드에서 인용) ) (및 String.format () 및 String.Join의 C # 자바 당량


# 4 층

이 작업을 수행 할 수 있습니다 :

String aToString = java.util.Arrays.toString(anArray);
// Do not need to do this if you are OK with '[' and ']'
aToString = aToString.substring(1, aToString.length() - 1);

또는 한 줄 (당신이 사용하는 [[과]] 시간을 원하지 않는 경우에만)

String aToString = java.util.Arrays.toString(anArray).substring(1).replaceAll("\\]$", "");

희망이 도움이됩니다.


하우스 # 5

당신은 아파치 코 몬즈 StringUtils에 연결 방법을 시도 할 수 있습니다 :

http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#join(java.util.Iterator,java.lang.String )

나는 ;-) 아파치 인 StringUtils는 JDK의 여유를 흡수 발견


하우스 # 6

당신이 어떤 외부 라이브러리 케이스없이 JDK를 사용하려는 경우, 당신은 올바른 방법입니다 코드가 있습니다. 의 JDK에는 간단한 "하나의 코드는 '없다.

외부 라이브러리를 사용할 수 있다면, 난 당신이 아파치 코 몬즈 도서관 보는 것이 좋습니다 org.apache.commons.lang.StringUtils의 클래스를.

사용 예제 :

List<String> list = Arrays.asList("Bill", "Bob", "Steve");
String joinedResult = StringUtils.join(list, " and ");

구축 # 7

하지 상자 밖으로하지만, 그러나 많은 라이브러리는 비슷한 기능을 가지고 있습니다 :

公地郎 :

org.apache.commons.lang.StringUtils.join(list, conjunction);

봄 :

org.springframework.util.StringUtils.collectionToDelimitedString(list, conjunction);

구축 # 8

구글의 구아바 API도 ()에도 불구하고 (이것은 다른 답변에서 자명하다) .join이, 아파치 코 몬즈 여기에 거의 표준입니다.


하우스 # 9

편집

나는 또한 눈치 toString()기본이되는 구현 문제 및 구분 기호 관련된 요소를 포함하고 있지만, 나는 그가 매우 편집증 환자라고 생각합니다.

이 점에서 두 가지 의견이 있기 때문에, 그래서 대답은 변경할 수 있습니다 :

static String join( List<String> list , String replacement  ) {
    StringBuilder b = new StringBuilder();
    for( String item: list ) { 
        b.append( replacement ).append( item );
    }
    return b.toString().substring( replacement.length() );
}

그것은 원래의 문제와 매우 비슷합니다.

프로젝트에 전체 단지를 추가하지 않는 경우에 따라서, 당신은 그것을 사용할 수 있습니다.

나는 원래 코드가 잘못되지라고 생각합니다. 사실, 모든 사람이 (다른 많은 검증을했다하더라도) 거의 동일 다른 모습을 권장

이것은이다 아파치 2.0 라이선스.

public static String join(Iterator iterator, String separator) {
    // handle null, zero and one elements before building a buffer
    if (iterator == null) {
        return null;
    }
    if (!iterator.hasNext()) {
        return EMPTY;
    }
    Object first = iterator.next();
    if (!iterator.hasNext()) {
        return ObjectUtils.toString(first);
    }

    // two or more elements
    StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small
    if (first != null) {
        buf.append(first);
    }

    while (iterator.hasNext()) {
        if (separator != null) {
            buf.append(separator);
        }
        Object obj = iterator.next();
        if (obj != null) {
            buf.append(obj);
        }
    }
    return buf.toString();
}

우리는 지금, 덕분에 오픈 소스를 알고


하우스 # 10

아파치 코 몬즈에 대한 모든 참조는 (대부분의 사람들이 사용하는 것입니다) 물론,하지만 난의 동등한 생각 구아바의 소목 장이 더 나은 API가 있습니다.

당신은 다음과 같은 간단한 연결 케이스를 사용할 수 있습니다

Joiner.on(" and ").join(names)

그러나 쉽게 널 (null)을 처리 할 수 ​​있습니다 :

Joiner.on(" and ").skipNulls().join(names);

또는

Joiner.on(" and ").useForNull("[unknown]").join(names);

지도를 처리하기 위해 (내 경우의 사용에 우선 평민 - 랭은 충분하다)

Map<String, Integer> ages = .....;
String foo = Joiner.on(", ").withKeyValueSeparator(" is ").join(ages);
// Outputs:
// Bill is 25, Joe is 30, Betty is 35

이 등, 디버깅에 유용


하우스 # 11

책임의 범위 내에서 JDK를 사용하는 순수 재미있는 방법 :

String[] array = new String[] { "Bill", "Bob", "Steve","[Bill]","1,2,3","Apple ][" };
String join = " and ";

String joined = Arrays.toString(array).replaceAll(", ", join)
        .replaceAll("(^\\[)|(\\]$)", "");

System.out.println(joined);

출력 :

빌과 밥과 스티브와 [빌] 및 1,2,3 애플] [


완벽한 미만은 매우 재미있는 방법이 아니다!

String[] array = new String[] { "7, 7, 7","Bill", "Bob", "Steve", "[Bill]",
        "1,2,3", "Apple ][" };
String join = " and ";

for (int i = 0; i < array.length; i++) array[i] = array[i].replaceAll(", ", "~,~");
String joined = Arrays.toString(array).replaceAll(", ", join)
        .replaceAll("(^\\[)|(\\]$)", "").replaceAll("~,~", ", ");

System.out.println(joined);

출력 :

7,7,7과 빌과 밥과 스티브와 [빌] 및 1,2,3 애플] [


하우스 # 12

새로운 함수를 정의하여 정통 방법 :

public static String join(String joinStr, String... strings) {
    if (strings == null || strings.length == 0) {
        return "";
    } else if (strings.length == 1) {
        return strings[0];
    } else {
        StringBuilder sb = new StringBuilder(strings.length * 1 + strings[0].length());
        sb.append(strings[0]);
        for (int i = 1; i < strings.length; i++) {
            sb.append(joinStr).append(strings[i]);
        }
        return sb.toString();
    }
}

샘플 :

String[] array = new String[] { "7, 7, 7", "Bill", "Bob", "Steve",
        "[Bill]", "1,2,3", "Apple ][","~,~" };

String joined;
joined = join(" and ","7, 7, 7", "Bill", "Bob", "Steve", "[Bill]", "1,2,3", "Apple ][","~,~");
joined = join(" and ", array); // same result

System.out.println(joined);

출력 :

7,7,7과 빌과 밥과 스티브와 [빌]과 2,3과 애플] [와 ~, ~


하우스 # 13

이 시도 :

java.util.Arrays.toString(anArray).replaceAll(", ", ",")
                .replaceFirst("^\\[","").replaceFirst("\\]$","");

하우스 # 14

당신이 사용하는 경우 이클립스에게 컬렉션 (이전 컬렉션을 GS ), 당신은 사용할 수있는 makeString()방법을.

List<String> list = Arrays.asList("Bill", "Bob", "Steve");

String string = ListAdapter.adapt(list).makeString(" and ");

Assert.assertEquals("Bill and Bob and Steve", string);

당신이 할 수있는 경우 List이클립스 컬렉션 형식을 변환, 당신은 어댑터를 제거 얻을 수 있습니다.

MutableList<String> list = Lists.mutable.with("Bill", "Bob", "Steve");
String string = list.makeString(" and ");

쉼표 만이 문자열을 구분하면, 매개 변수없이 사용할 수있는 makeString()버전.

Assert.assertEquals(
    "Bill, Bob, Steve", 
    Lists.mutable.with("Bill", "Bob", "Steve").makeString());

참고 : 나는 제출자의 이클립스 컬렉션입니다.


하우스 # 15

제 3 자 라이브러리가이 작업을 수행 할 수 있습니다 사용 자바 8, 당신은 필요가 없습니다.

문자열이 컬렉션에 추가되면, 새로운 사용 String.Join () 방법 :

List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"

유형이 컬렉션 문자열, 스트림 API 아니며, 경우에 당신은 할 수 있습니다 추가 된 수집기와 함께 사용 :

List<Person> list = Arrays.asList(
  new Person("John", "Smith"),
  new Person("Anna", "Martinez"),
  new Person("Paul", "Watson ")
);

String joinedFirstNames = list.stream()
  .map(Person::getFirstName)
  .collect(Collectors.joining(", ")); // "John, Anna, Paul"

StringJoiner클래스도 유용 할 수 있습니다.


하우스 # 16

그것은이 java.util.StringJoiner자바 (8) 솔루션

자바 8은이 StringJoiner클래스를. 그러나 당신은 여전히 자바와 같이, 일부 상용구를 작성해야합니다.

StringJoiner sj = new StringJoiner(" and ", "" , "");
String[] names = {"Bill", "Bob", "Steve"};
for (String name : names) {
   sj.add(name);
}
System.out.println(sj);

하우스 # 17

사용 자바 8 수집가, 다음 코드는이 작업을 수행 할 수 있습니다

Arrays.asList("Bill", "Bob", "Steve").stream()
.collect(Collectors.joining(" and "));

또한, 자바 (8)는 가장 간단한 솔루션입니다 :

String.join(" and ", "Bill", "Bob", "Steve");

또는

String.join(" and ", Arrays.asList("Bill", "Bob", "Steve"));

하우스 # 18

세 가지 가능성 자바 8 :

List<String> list = Arrays.asList("Alice", "Bob", "Charlie")

String result = String.join(" and ", list);

result = list.stream().collect(Collectors.joining(" and "));

result = list.stream().reduce((t, u) -> t + " and " + u).orElse("");

하우스 # 19

에 안드로이드, 당신은 사용할 수 있습니다 TextUtils의 클래스를.

TextUtils.join(" and ", names);

하우스 # 20

당신은 StringUtils에 스프링 프레임 워크의에서 사용할 수 있습니다. 내가 이미 언급 알고 있지만 실제로이 코드는 봄없이 바로 사용할 수 있습니다 사용할 수 있습니다.

// from https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/util/StringUtils.java

/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class StringUtils {
    public static String collectionToDelimitedString(Collection<?> coll, String delim, String prefix, String suffix) {
        if(coll == null || coll.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        Iterator<?> it = coll.iterator();
        while (it.hasNext()) {
            sb.append(prefix).append(it.next()).append(suffix);
            if (it.hasNext()) {
                sb.append(delim);
            }
        }
        return sb.toString();
    }
}

하우스 # 21

자바 8 가져온

Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

방법은 사용하여 prefix + suffixNULL 값이 안전 나타낸다.

다음과 같은 방법으로 사용할 수 있습니다 :

String s = stringList.stream().collect(Collectors.joining(" and ", "prefix_", "_suffix"))

Collectors.joining(CharSequence delimiter)방법은 단지 내에서 호출 joining(delimiter, "", "").


하우스 # 22

자바 1.8를 사용하면 스트림을 사용할 수 있습니다,

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
List<String> list = Arrays.asList("Bill","Bob","Steve").
String str = list.stream().collect(Collectors.joining(" and "));
원저는 0 출판 · 원의 칭찬 0 · 조회수 2226

추천

출처blog.csdn.net/p15097962069/article/details/103906204