简体   繁体   English

Java function 对于 arrays 像 PHP 的 join()?

[英]Java function for arrays like PHP's join()?

I want to join a String[] with a glue string.我想用胶水字符串加入String[] Is there a function for this?这个有 function 吗?

Starting from Java8 it is possible to use String.join() .Java8开始,可以使用String.join()

String.join(", ", new String[]{"Hello", "World", "!"})

Generates:产生:

Hello, World, !

Otherwise, Apache Commons Lang has a StringUtils class which has a join function which will join arrays together to make a String .否则, Apache Commons Lang有一个StringUtils类,它有一个join函数,可以将数组连接在一起形成一个String

For example:例如:

StringUtils.join(new String[] {"Hello", "World", "!"}, ", ")

Generates the following String :生成以下String

Hello, World, !

If you were looking for what to use in android, it is:如果您正在寻找在 android 中使用什么,它是:

String android.text.TextUtils.join(CharSequence delimiter, Object[] tokens)

for example:例如:

String joined = TextUtils.join(";", MyStringArray);

In Java 8 you can use在 Java 8 中,您可以使用

1) Stream API : 1)流API:

String[] a = new String[] {"a", "b", "c"};
String result = Arrays.stream(a).collect(Collectors.joining(", "));

2) new String.join method: https://stackoverflow.com/a/21756398/466677 2)新的String.join方法: https ://stackoverflow.com/a/21756398/466677

3) java.util.StringJoiner class: http://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html 3) java.util.StringJoiner 类: http : //docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html

You could easily write such a function in about ten lines of code:你可以很容易地用大约十行代码编写这样一个函数:

String combine(String[] s, String glue)
{
  int k = s.length;
  if ( k == 0 )
  {
    return null;
  }
  StringBuilder out = new StringBuilder();
  out.append( s[0] );
  for ( int x=1; x < k; ++x )
  {
    out.append(glue).append(s[x]);
  }
  return out.toString();
}

A little mod instead of using substring():一个小的 mod 而不是使用 substring():

//join(String array,delimiter)
public static String join(String r[],String d)
{
        if (r.length == 0) return "";
        StringBuilder sb = new StringBuilder();
        int i;
        for(i=0;i<r.length-1;i++){
            sb.append(r[i]);
            sb.append(d);
        }
        sb.append(r[i]);
        return sb.toString();
}

As with many questions lately, Java 8 to the rescue:与最近的许多问题一样,Java 8 来拯救:


Java 8 added a new static method to java.lang.String which does exactly what you want: Java 8 向java.lang.String添加了一个新的静态方法,它完全符合您的要求:

public static String join(CharSequence delimeter, CharSequence... elements);

Using it:使用它:

String s = String.join(", ", new String[] {"Hello", "World", "!"});

Results in:结果是:

"Hello, World, !"

Google guava's library also has this kind of capability . Google guava 的库也有这种能力 You can see the String[] example also from the API.您也可以从 API 中看到 String[] 示例。

As already described in the api, beware of the immutability of the builder methods.正如 api 中已经描述的那样,要注意构建器方法的不变性。

It can accept an array of objects so it'll work in your case.它可以接受一组对象,因此它适用于您的情况。 In my previous experience, i tried joining a Stack which is an iterable and it works fine.在我之前的经验中,我尝试加入一个可迭代的 Stack,它工作正常。

Sample from me :我的样品:

Deque<String> nameStack = new ArrayDeque<>();
nameStack.push("a coder");
nameStack.push("i am");
System.out.println("|" + Joiner.on(' ').skipNulls().join(nameStack) + "|");

prints out : |i am a coder|打印出: |i am a coder|

If you are using the Spring Framework then you have the StringUtils class:如果您使用的是Spring Framework,那么您将拥有StringUtils类:

import static org.springframework.util.StringUtils.arrayToDelimitedString;

arrayToDelimitedString(new String[] {"A", "B", "C"}, "\n");

Given:鉴于:

String[] a = new String[] { "Hello", "World", "!" };

Then as an alternative to coobird's answer, where the glue is ", ":然后作为 coobird 答案的替代,其中胶水是“,”:

Arrays.asList(a).toString().replaceAll("^\\[|\\]$", "")

Or to concatenate with a different string, such as " &amp; ".或者连接不同的字符串,例如“ &amp; ”。

Arrays.asList(a).toString().replaceAll(", ", " &amp; ").replaceAll("^\\[|\\]$", "")

However... this one ONLY works if you know that the values in the array or list DO NOT contain the character string ", ".但是……只有当您知道数组或列表中的值不包含字符串“,”时,此方法才有效。

Not in core, no.不在核心,不。 A search for "java array join string glue" will give you some code snippets on how to achieve this though.搜索“java array join string paste”将为您提供一些关于如何实现这一点的代码片段。

eg例如

public static String join(Collection s, String delimiter) {
    StringBuffer buffer = new StringBuffer();
    Iterator iter = s.iterator();
    while (iter.hasNext()) {
        buffer.append(iter.next());
        if (iter.hasNext()) {
            buffer.append(delimiter);
        }
    }
    return buffer.toString();
}

If you've landed here looking for a quick array-to-string conversion, try Arrays.toString() .如果您来到这里寻找快速的数组到字符串转换,请尝试Arrays.toString()

Creates a String representation of the Object[] passed.创建传递的Object[]的字符串表示形式。 The result is surrounded by brackets ( "[]" ), each element is converted to a String via the String.valueOf(Object) and separated by ", " .结果用方括号 ( "[]" ) 括起来,每个元素通过String.valueOf(Object)转换为 String 并用", "分隔。 If the array is null , then "null" is returned.如果数组为null ,则返回"null"

Just for the "I've the shortest one" challenge, here are mines ;)只是为了“我有最短的”挑战,这里有我的 ;)

Iterative:迭代:

public static String join(String s, Object... a) {
    StringBuilder o = new StringBuilder();
    for (Iterator<Object> i = Arrays.asList(a).iterator(); i.hasNext();)
        o.append(i.next()).append(i.hasNext() ? s : "");
    return o.toString();
}

Recursive:递归:

public static String join(String s, Object... a) {
    return a.length == 0 ? "" : a[0] + (a.length == 1 ? "" : s + join(s, Arrays.copyOfRange(a, 1, a.length)));
}

Nothing built-in that I know of.我所知道的没有内置的东西。

Apache Commons Lang has a class called StringUtils which contains many join functions. Apache Commons Lang有一个名为StringUtils的类,它包含许多连接函数。

This is how I do it.我就是这样做的。

private String join(String[] input, String delimiter)
{
    StringBuilder sb = new StringBuilder();
    for(String value : input)
    {
        sb.append(value);
        sb.append(delimiter);
    }
    int length = sb.length();
    if(length > 0)
    {
        // Remove the extra delimiter
        sb.setLength(length - delimiter.length());
    }
    return sb.toString();
}

A similar alternative一个类似的选择

/**
 * @param delimiter 
 * @param inStr
 * @return String
 */
public static String join(String delimiter, String... inStr)
{
    StringBuilder sb = new StringBuilder();
    if (inStr.length > 0)
    {
        sb.append(inStr[0]);
        for (int i = 1; i < inStr.length; i++)
        {
            sb.append(delimiter);                   
            sb.append(inStr[i]);
        }
    }
    return sb.toString();
}

My spin.我的旋转。

public static String join(Object[] objects, String delimiter) {
  if (objects.length == 0) {
    return "";
  }
  int capacityGuess = (objects.length * objects[0].toString().length())
      + ((objects.length - 1) * delimiter.length());
  StringBuilder ret = new StringBuilder(capacityGuess);
  ret.append(objects[0]);
  for (int i = 1; i < objects.length; i++) {
    ret.append(delimiter);
    ret.append(objects[i]);
  }
  return ret.toString();
}

public static String join(Object... objects) {
  return join(objects, "");
}

Do you like my 3-lines way using only String class's methods?你喜欢我只使用 String 类的方法的 3 行方式吗?

static String join(String glue, String[] array) {
    String line = "";
    for (String s : array) line += s + glue;
    return (array.length == 0) ? line : line.substring(0, line.length() - glue.length());
}

To get "str1, str2" from "str1", "str2", "" :要从 "str1", "str2", "" 获取 "str1, str2" :

Stream.of("str1", "str2", "").filter(str -> !str.isEmpty()).collect(Collectors.joining(", ")); 

Also you can add extra null-check您也可以添加额外的空检查

In case you're using Functional Java library and for some reason can't use Streams from Java 8 (which might be the case when using Android + Retrolambda plugin), here is a functional solution for you:如果您正在使用 Functional Java 库并且由于某种原因不能使用来自 Java 8 的 Streams(使用 Android + Retrolambda 插件时可能会出现这种情况),这里有一个功能解决方案供您使用:

String joinWithSeparator(List<String> items, String separator) {
    return items
            .bind(id -> list(separator, id))
            .drop(1)
            .foldLeft(
                    (result, item) -> result + item,
                    ""
            );
}

Note that it's not the most efficient approach, but it does work good for small lists.请注意,这不是最有效的方法,但它确实适用于小型列表。

Whatever approach you choose, be aware of null values in the array.无论您选择哪种方法,都要注意数组中的空值。 Their string representation is "null" so if it is not your desired behavior, skip null elements.它们的字符串表示为“null”,因此如果这不是您想要的行为,请跳过 null 元素。

String[] parts = {"Hello", "World", null, "!"};
Stream.of(parts)
      .filter(Objects::nonNull)
      .collect(Collectors.joining(" "));

As already mentioned, class StringJoiner is also an available option since Java 8:如前所述,class StringJoiner也是一个可用选项,因为 Java 8:

@NotNull
String stringArrayToCsv(@NotNull String[] data) {
    if (data.length == 0) {return "";}
    StringJoiner joiner = new StringJoiner(", ");
    Iterator<String> itr = Arrays.stream(data).iterator();
    while (itr.hasNext()) {joiner.add(itr.next());}
    return joiner.toString();
}

However, the traditional String.join() is less imports and less code:但是,传统的String.join()导入更少,代码更少:

@NotNull
String stringArrayToCsv(@NotNull String[] data) {
    if (data.length == 0) {return "";}
    return String.join(", ", data);
}

I do it this way using a StringBuilder:我使用 StringBuilder 这样做:

public static String join(String[] source, String delimiter) {
    if ((null == source) || (source.length < 1)) {
        return "";
    }

    StringBuilder stringbuilder = new StringBuilder();
    for (String s : source) {
        stringbuilder.append(s + delimiter);
    }
    return stringbuilder.toString();
} // join((String[], String)

There is simple shorthand technique I use most of the times..我大部分时间都使用简单的速记技巧。

String op = new String;
for (int i : is) 
{
    op += candidatesArr[i-1]+",";
}
op = op.substring(0, op.length()-1);

java.util.Arrays has an 'asList' method. java.util.Arrays 有一个“asList”方法。 Together with the java.util.List/ArrayList API this gives you all you need:;与 java.util.List/ArrayList API 一起为您提供所需的一切:;

private static String[] join(String[] array1, String[] array2) {

    List<String> list = new ArrayList<String>(Arrays.asList(array1));
    list.addAll(Arrays.asList(array2));
    return list.toArray(new String[0]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM