📜  木工班 |番石榴 |Java

📅  最后修改于: 2022-05-13 01:55:23.829000             🧑  作者: Mango

木工班 |番石榴 |Java

Guava 的Joiner 类提供了各种方法来处理对字符串、对象等的连接操作。这个类为连接操作提供了高级功能。

声明:以下是com.google.common.base.Joiner类的声明:

@GwtCompatible
public class Joiner
   extends Object

下表简要总结了 Guava 的 Joiner 类提供的方法:

例子:

// Java code to show implementation of
// Guava's Joiner class's method
  
import com.google.common.base.Joiner;
import java.util.*;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
  
        // Creating a string array
        String[] arr = { "one", "two", "three", "four" };
        System.out.println("Original Array: "
                           + Arrays.toString(arr));
  
        // Use Joiner to combine all elements.
        // ... Specify delimiter in on method.
  
        // The last part of the Joiner statement, join,
        // can receive an Iterable (like an ArrayList) or
        // an Object array. It returns a String.
        String result = Joiner.on("...")
                            .join(arr);
  
        System.out.println("Joined String: "
                           + result);
    }
}
输出:
Original Array: [one, two, three, four]
Joined String: one...two...three...four

Guava 的 Joiner 类提供的更多方法是:

例子:

// Java code to show implementation of
// Guava's Joiner class's method
  
import com.google.common.base.Joiner;
import java.util.*;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
  
        // Creating a string array
        String[] arr = { "one", "two", null,
                         "four", null, "five" };
        System.out.println("Original Array: "
                           + Arrays.toString(arr));
  
        // Unlike the standard join method, we can
        // filter elements with a Joiner. With skipNulls,
        // null elements in an array or Iterable are removed.
        // Often null elements are not needed.
        // $$ Specify delimiter in on method.
  
        // The last part of the Joiner statement, join,
        // can receive an Iterable (like an ArrayList) or
        // an Object array. It returns a String.
        String result = Joiner.on('+')
                            .skipNulls()
                            .join(arr);
  
        System.out.println("Joined String: "
                           + result);
    }
}
输出:
Original Array: [one, two, null, four, null, five]
Joined String: one+two+four+five

参考: Google Guava Joiner 类