Java: convert List to a String

前端 未结 22 2608
日久生厌
日久生厌 2020-11-22 01:03

JavaScript has Array.join()

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

Does Java have anything

相关标签:
22条回答
  • 2020-11-22 01:56

    All the references to Apache Commons are fine (and that is what most people use) but I think the Guava equivalent, Joiner, has a much nicer API.

    You can do the simple join case with

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

    but also easily deal with nulls:

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

    or

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

    and (useful enough as far as I'm concerned to use it in preference to commons-lang), the ability to deal with Maps:

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

    which is extremely useful for debugging etc.

    0 讨论(0)
  • 2020-11-22 01:56

    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();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 01:56

    Try this:

    java.util.Arrays.toString(anArray).replaceAll(", ", ",")
                    .replaceFirst("^\\[","").replaceFirst("\\]$","");
    
    0 讨论(0)
  • 2020-11-22 01:57

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

    List<String> list = Arrays.asList("Bill", "Bob", "Steve");
    
    String string = ListAdapter.adapt(list).makeString(" and ");
    
    Assert.assertEquals("Bill and Bob and Steve", string);
    

    If you can convert your List to an Eclipse Collections type, then you can get rid of the adapter.

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

    If you just want a comma separated string, you can use the version of makeString() that takes no parameters.

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

    Note: I am a committer for Eclipse Collections.

    0 讨论(0)
提交回复
热议问题