JavaScript具有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的一部分,那么这样做是没有意义的。
#1楼
我写了这个(我将它用于bean并利用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楼
不,标准Java API中没有这样的便捷方法。
毫不奇怪,如果您不想自己编写,Apache Commons 在其StringUtils类中提供了这种功能。
#3楼
您可以使用具有StringUtils类和join方法的apache commons库。
检查此链接: https : //commons.apache.org/proper/commons-lang/javadocs/api.2.0/org/apache/commons/lang/StringUtils.html
请注意,随着时间的推移,上面的链接可能会过时,在这种情况下,您可以在网上搜索“ apache commons StringUtils”,这将使您找到最新的参考资料。
(从该线程引用) C#的Java等价String.Format()和String.Join()
#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楼
您可能想尝试Apache Commons StringUtils连接方法:
我发现Apache StringUtils吸收了jdk的懈怠;-)
#6楼
如果您想在没有任何外部库的情况下使用JDK,那么您拥有的代码就是正确的方法。 在JDK中没有简单的“单一代码”。
如果可以使用外部库,建议您查看Apache Commons库中的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楼
谷歌的Guava API也具有.join(),尽管(在其他答复中应该很明显),Apache Commons几乎是这里的标准。
#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() );
}
看起来与原始问题非常相似。
因此,如果您不想将整个jar添加到您的项目中,则可以使用它。
我认为您的原始代码没有错。 实际上,每个人都建议的替代方案看起来几乎相同(尽管它进行了许多其他验证)
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楼
所有对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使用就足够了)能够处理Maps:
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);
输出:
Bill and Bob and Steve and [Bill] and 1,2,3 and 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] [
#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以及Bill和Bob和Steve以及[Bill]和1,2,3以及Apple] [和〜,〜
#13楼
尝试这个:
java.util.Arrays.toString(anArray).replaceAll(", ", ",")
.replaceFirst("^\\[","").replaceFirst("\\]$","");
#14楼
如果您使用的是Eclipse Collections (以前称为GS Collections ),则可以使用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 Collections类型,则可以摆脱适配器。
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的提交者。
#15楼
使用Java 8,您无需任何第三方库就可以做到这一点。
如果要加入字符串集合,则可以使用新的String.join()方法:
List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"
如果您的Collection的类型不是String,则可以将Stream API与加入的Collector一起使用 :
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
Java 8解决方案
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);
#17楼
使用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"));
#18楼
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("");
#19楼
在Android上,您可以使用TextUtils类。
TextUtils.join(" and ", names);
#20楼
您可以从Spring Framework的StringUtils中使用它。 我知道已经提到过它,但是实际上您可以使用此代码即可立即使用,而无需Spring。
// 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楼
Java 8确实带来了
Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
方法,通过使用prefix + suffix
表示空值是安全的。
可以按以下方式使用它:
String s = stringList.stream().collect(Collectors.joining(" and ", "prefix_", "_suffix"))
Collectors.joining(CharSequence delimiter)
方法仅在内部调用joining(delimiter, "", "")
。
#22楼
有了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 "));