Is there a utility way to split a list by a given string?

Is there something like the following in Apache Common Langor Spring Utilsor are you writing your own Util method for this?

List<String> list = new ArrayList<String>();
list.add("moo");
list.add("foo");
list.add("bar");

String enumeratedList = Util.enumerate(list, ", ");

assert enumeratedList == "moo, foo, bar";

I remember using implodein php, here is what I am looking for for java.

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
+3
source share
3 answers

You can use StringUtils.join(Object[] array, String delimiter)(from commons-lang) as follows:

String enumeratedList = StringUtils.join(list.toArray(), ", ");
+11
source

Google Collections provides a Joiner class that can be used as follows:

public class Main {

    public static void main(String[] args) {
        List<String> list = Lists.newLinkedList();
        list.add("1");
        list.add("2");
        list.add("3");
        System.out.println(Joiner.on(", ").join(list));
    }

}
+4
source

This is pretty trivial to complement if you don't want a dependency on commons-lang. It is also nice to convert a list to an array just to reattach it to a String. Instead, just iterate over your collection. Even better than using Collection, iterable uses which handles everything that can be an iterator (even some stream or collection of unknown length).

import java.util.Arrays;
import java.util.Iterator;

public class JoinDemo {
  public static String join(String sep, Iterable<String> i) {
    StringBuilder sb = new StringBuilder();
    for (Iterator<String> it = i.iterator(); it.hasNext();) {
      sb.append(it.next());
      if (it.hasNext())
        sb.append(sep);
    }
    return sb.toString();
  }

  public static void main(String[] args) {
    System.out.println(join(",", Arrays.asList(args)));
  }
}

Example:

# javac JoinDemo.java
# java JoinDemo a b c
a,b,c
+3
source

Source: https://habr.com/ru/post/1736312/


All Articles