Java:将List<string>转换为字符串JavaScriptArray.join()js>["Bill","Bob","Steve"].join(" and ")Bill and Bob and SteveJava有类似的东西吗?我知道我可以用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的一部分,那么这样做是没有意义的。
3 回答
BIG阳
TA贡献1859条经验 获得超6个赞
List<String> list = Arrays.asList("foo", "bar", "baz");String joined = String.join(" and ", list); // "foo and bar and baz"
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
繁星点点滴滴
TA贡献1803条经验 获得超3个赞
org.apache.commons.lang.StringUtils.join(list, conjunction);
org.springframework.util.StringUtils.collectionToDelimitedString(list, conjunction);
添加回答
举报
0/150
提交
取消