用逗号和“和”</string>连接Java中的List <string>

时间:2011-11-24 09:52:24

标签: java join apache-commons

给出一个清单

List<String> l = new ArrayList<String>();
l.add("one");
l.add("two");
l.add("three");

我有一个方法

String join(List<String> messages) {
        if (messages.isEmpty()) return "";
        if (messages.size() == 1) return messages.get(0);
        String message = "";
        message = StringUtils.join(messages.subList(0, messages.size() -2), ", ");
        message = message + (messages.size() > 2 ? ", " : "") + StringUtils.join(messages.subList(messages.size() -2, messages.size()), ", and ");
        return message;
    }

,对于l,产生&#34;一,二和三&#34;。 我的问题是,是否有一个标准(apache-commons)方法做同样的事情?,例如

WhatEverUtils.join(l, ", ", ", and ");

澄清。我的问题是没有让这种方法起作用。它就像我想要的那样工作,经过测试,一切都很顺利。我的问题是我找不到一些实现这种功能的类似apache-commons的模块。这让我感到惊讶,因为我不能成为第一个需要这个的人。

但也许其他人刚刚完成了

StringUtils.join(l, ", ").replaceAll(lastCommaRegex, ", and");

8 个答案:

答案 0 :(得分:51)

在Java 8中,您可以使用String.join(),如下所示:

Collection<String> elements = ....;
String result = String.join(", ", elements);

答案 1 :(得分:17)

来自join的内容如下: org.apache.commons.lang.StringUtils

示例:

StringUtils.join(new String[] { "one", "two", "three" }, ", "); // one, two, three

要使用“和”或“,和”,您可以简单地替换最后一个逗号。

答案 2 :(得分:14)

我喜欢将谷歌收藏用于此目的。整洁而且非常有用:

Joiner.on(",").join(myList)

这种代码已经一次又一次地编写,你应该自由地实现你的特定实现逻辑。

如果你使用maven,那么依赖:

<dependency>
  <groupId>com.google.collections</groupId>
  <artifactId>google-collections</artifactId>
  <version>1.0</version>
</dependency>

它还有许多其他很酷的功能!

编辑:为了完整起见,这将生成“一,二,三”列表。

List<String> originalList = Arrays.asList("one", "two", "three");
Joiner.on(", ").join(originalList.subList(0, originalList.size() - 1))
  .concat(", and ").concat(originalList.get(originalList.size() - 1));

答案 3 :(得分:10)

使用Java 8,您可以将流与加入者一起使用。

Collection<String> strings;
...
String commaDelimited = strings.stream().collect(Collectors.joining(","));
// use strings.parallelStream() instead, if you think
//   there are gains to be had by doing fork/join

答案 4 :(得分:4)

其他答案谈及“替换最后一个逗号”,如果最后一个术语本身包含逗号,则不安全。

不是使用库,而是使用一行(尽管很长)的JDK代码:

public static String join(List<String> msgs) {
    return msgs == null || msgs.size() == 0 ? "" : msgs.size() == 1 ? msgs.get(0) : msgs.subList(0, msgs.size() - 1).toString().replaceAll("^.|.$", "") + " and " + msgs.get(msgs.size() - 1);
}

请参阅处理所有边缘情况的此代码的live demo


仅供参考,这是一个更具可读性的双线:

public static String join(List<String> msgs) {
    int size = msgs == null ? 0 : msgs.size();
    return size == 0 ? "" : size == 1 ? msgs.get(0) : msgs.subList(0, --size).toString().replaceAll("^.|.$", "") + " and " + msgs.get(size);
}

答案 5 :(得分:3)

要使用英语生成语法输出,在连接字符串列表时需要考虑3种情况:

  1. “A”

  2. “A和B”

  3. “A,B和C。

  4. 这可以使用标准Java或Guava完成,如下所示。解决方案基本相同,只是偏好您想要使用的。

    import com.google.common.base.Joiner;
    import com.google.common.collect.ImmutableList;
    
    import org.junit.Test;
    
    import java.util.List;
    
    import static org.junit.Assert.assertEquals;
    
    public class JoinListTest {
    
        @Test
        public void test_join() {
            // create cases (don't need to use ImmutableList builder from guava)
            final List<String> case1 = new ImmutableList.Builder<String>().add("A").build();
            final List<String> case2 = new ImmutableList.Builder<String>().add("A", "B").build();
            final List<String> case3 = new ImmutableList.Builder<String>().add("A", "B", "C").build();
            // test with standard java
            assertEquals("A", joinListGrammaticallyWithJava(case1));
            assertEquals("A and B", joinListGrammaticallyWithJava(case2));
            assertEquals("A, B, and C", joinListGrammaticallyWithJava(case3));
            // test with guava
            assertEquals("A", joinListGrammaticallyWithGuava(case1));
            assertEquals("A and B", joinListGrammaticallyWithGuava(case2));
            assertEquals("A, B, and C", joinListGrammaticallyWithGuava(case3));
        }
    
        private String joinListGrammaticallyWithJava(final List<String> list) {
            return list.size() > 1
                    ? String.join(", ", list.subList(0, list.size() - 1))
                        .concat(String.format("%s and ", list.size() > 2 ? "," : ""))
                        .concat(list.get(list.size() - 1))
                    : list.get(0);
        }
    
        private String joinListGrammaticallyWithGuava(final List<String> list) {
            return list.size() > 1
                    ? Joiner.on(", ").join(list.subList(0, list.size() - 1))
                        .concat(String.format("%s and ", list.size() > 2 ? "," : ""))
                        .concat(list.get(list.size() - 1))
                    : list.get(0);
        }
    
    }
    

答案 6 :(得分:0)

我不知道任何支持在加入的String中添加and的Apache String连接器。

这是一个未经测试的代码,可以执行您的要求:

public static String join(String separator, List<String> mList, boolean includeAndInText) {
    StringBuilder sb = new StringBuilder();
    int count = 0;

    for (String m: mList) {
        if (includeAndInText && (count + 1 != mList.size())) {
            sb.append (" and ");
        }

        sb.append(m);
        count++;
        if (count < mList.size()) {
            sp.append(separator);
        }       
    }

    return sb.toString();
}

答案 7 :(得分:0)

Bohemian♦答案的改进版本。您可以选择删除针对个人偏好设置为空的项目。

/** Auto Concat Wrapper
 *  Wraps a list of string with comma and concat the last element with "and" string.
 *  E.g: List["A", "B", "C", "D"] -> Output: "A, B, C and D"
 * @param elements
 */
public static String join(List<String> elements){
    if(elements==null){return "";}
    List<String> tmp = new ArrayList<>(elements);
    tmp.removeAll(Collections.singleton(null)); //Remove all nulled items

    int size = tmp.size();
    return size == 0 ? "" : size == 1 ? tmp.get(0) : String.join(", ", tmp.subList(0, --size)).concat(" and ").concat(tmp.get(size));
}

测试结果:

List<String> w = Arrays.asList("A");
List<String> x = Arrays.asList("A", "B");
List<String> y = Arrays.asList("A", "B", null, "C");
List<String> z = Arrays.asList("A", "B", "C", "D");
System.out.println(join(w));//A
System.out.println(join(x));//A and B
System.out.println(join(y));//A, B and C
System.out.println(join(z));//A, B, C and D