자바 : 목록 변환 문자열에
자바 스크립트는 Array.join()
js>["Bill","Bob","Steve"].join(" and ")
Bill and Bob and Steve
Java에 이와 같은 것이 있습니까? 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의 일부인 경우에는이 작업을 수행 할 필요가 없습니다.
Java 8을 사용하면 타사 라이브러리없이이 작업을 수행 할 수 있습니다.
문자열 컬렉션에 가입하려면 새로운 String.join () 메서드를 사용할 수 있습니다 .
List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"
String이 아닌 다른 유형의 Collection이있는 경우 결합하는 Collector 와 함께 Stream 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
클래스는 유용 할 수 있습니다.
Apache Commons에 대한 모든 참조는 괜찮지 만 (대부분의 사람들이 사용하는 것입니다) Guava에 해당하는 Joiner 가 훨씬 더 좋은 API를 가지고 있다고 생각합니다 .
간단한 조인 케이스는
Joiner.on(" and ").join(names)
또한 null을 쉽게 처리 할 수 있습니다.
Joiner.on(" and ").skipNulls().join(names);
또는
Joiner.on(" and ").useForNull("[unknown]").join(names);
그리고 (내가 commons-lang보다 우선적으로 사용하는 한 충분히 유용함),지도를 다루는 능력 :
Map<String, Integer> ages = .....;
String foo = Joiner.on(", ").withKeyValueSeparator(" is ").join(ages);
// Outputs:
// Bill is 25, Joe is 30, Betty is 35
디버깅 등에 매우 유용합니다.
즉시 사용할 수는 없지만 많은 라이브러리에 다음과 같은 유사한 기능이 있습니다.
Commons Lang :
org.apache.commons.lang.StringUtils.join(list, conjunction);
봄:
org.springframework.util.StringUtils.collectionToDelimitedString(list, conjunction);
에 안드로이드 당신은 사용할 수 TextUtils의 클래스를.
TextUtils.join(" and ", names);
아니요, 표준 Java API에는 이러한 편리한 방법이 없습니다.
당연히 Apache Commons는 사용자가 직접 작성하고 싶지 않은 경우를 대비 하여 StringUtils 클래스 에 이러한 기능을 제공합니다 .
Java 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("");
Java 8 컬렉터를 사용하면 다음 코드로이를 수행 할 수 있습니다.
Arrays.asList("Bill", "Bob", "Steve").stream()
.collect(Collectors.joining(" and "));
또한 Java 8에서 가장 간단한 솔루션입니다.
String.join(" and ", "Bill", "Bob", "Steve");
또는
String.join(" and ", Arrays.asList("Bill", "Bob", "Steve"));
나는 이것을 썼다 (나는 그것을 bean과 exploit 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();
}
그러나 Collection
JSP에서 지원하지 않으므로 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, ", ")}
가지고있는 코드는 외부 라이브러리없이 JDK를 사용하려는 경우 올바른 방법입니다. JDK에서 사용할 수있는 단순한 "한 줄짜리"는 없습니다.
외부 라이브러리를 사용할 수 있다면 Apache Commons 라이브러리의 org.apache.commons.lang.StringUtils 클래스 를 살펴 보는 것이 좋습니다 .
사용 예 :
List<String> list = Arrays.asList("Bill", "Bob", "Steve");
String joinedResult = StringUtils.join(list, " and ");
이를 달성하는 정통 방법은 새로운 기능을 정의하는 것입니다.
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 그리고 Bill과 Bob과 Steve와 [Bill]과 1,2,3과 Apple] [그리고 ~, ~
StringUtils 클래스와 조인 메서드가있는 아파치 공용 라이브러리를 사용할 수 있습니다.
이 링크를 확인하십시오 : https://commons.apache.org/proper/commons-lang/javadocs/api.2.0/org/apache/commons/lang/StringUtils.html
위 링크는 시간이 지남에 따라 쓸모 없게 될 수 있습니다.이 경우 웹에서 "apache commons StringUtils"를 검색하면 최신 참조를 찾을 수 있습니다.
(이 스레드에서 참조) Java는 C # String.Format () 및 String.Join ()에 해당합니다.
Java 8 솔루션 java.util.StringJoiner
Java 8에는 StringJoiner
클래스가 있습니다. 그러나 Java이기 때문에 약간의 상용구를 작성해야합니다.
StringJoiner sj = new StringJoiner(" and ", "" , "");
String[] names = {"Bill", "Bob", "Steve"};
for (String name : names) {
sj.add(name);
}
System.out.println(sj);
다음과 같이 할 수 있습니다.
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("\\]$", "");
도움이 되었기를 바랍니다.
하나의 의무 라인에서 순수한 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);
산출:
Bill과 Bob과 Steve와 [Bill]과 1,2,3과 Apple] [
너무 완벽하지 않고 너무 재미 있지 않은 방법!
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, Bill, Bob, Steve, [Bill], 1,2,3, Apple] [
Apache Commons StringUtils 조인 방법을 시도해 볼 수 있습니다.
http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#join(java.util.Iterator , java.lang.String)
Apache StringUtils가 jdk의 여유를 선택한다는 것을 발견했습니다 ;-)
당신이 사용하는 경우 이클립스 컬렉션 (구 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
Eclipse 콜렉션 유형으로 변환 할 수 있으면 어댑터를 제거 할 수 있습니다.
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());
참고 : 저는 Eclipse Collections의 커미터입니다.
Java 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 "));
Google's Guava API also has .join(), although (as should be obvious with the other replies), Apache Commons is pretty much the standard here.
EDIT
I also notice the toString()
underlying implementation issue, and about the element containing the separator but I thought I was being paranoid.
Since I've got two comments on that regard, I'm changing my answer to:
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() );
}
Which looks pretty similar to the original question.
So if you don't feel like adding the whole jar to your project you may use this.
I think there's nothing wrong with your original code. Actually, the alternative that everyone's is suggesting looks almost the same ( although it does a number of additional validations )
Here it is, along with the Apache 2.0 license.
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();
}
Now we know, thank you open source
Java 8 does bring the
Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
method, that is nullsafe by using prefix + suffix
for null values.
It can be used in the following manner:
String s = stringList.stream().collect(Collectors.joining(" and ", "prefix_", "_suffix"))
The Collectors.joining(CharSequence delimiter)
method just calls joining(delimiter, "", "")
internally.
You can use this from Spring Framework's StringUtils. I know it's already been mentioned, but you can actually just take this code and it works immediately, without needing Spring for it.
// 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();
}
}
Try this:
java.util.Arrays.toString(anArray).replaceAll(", ", ",")
.replaceFirst("^\\[","").replaceFirst("\\]$","");
참고URL : https://stackoverflow.com/questions/1751844/java-convert-liststring-to-a-string
'Programing' 카테고리의 다른 글
변수에 로컬 JSON 파일로드 (0) | 2020.10.05 |
---|---|
AngularJS의 ng-options에서 값 속성을 어떻게 설정합니까? (0) | 2020.10.04 |
Vim에서 커서를 이동하지 않고 화면을 이동하는 방법은 무엇입니까? (0) | 2020.10.04 |
생성 알고리즘과 차별 알고리즘의 차이점은 무엇입니까? (0) | 2020.10.04 |
목록 변경 사항 목록이 예기치 않게 하위 목록에 반영됨 (0) | 2020.10.04 |