Location>code7788 >text

Joiner and Splitter in Guava

Popularity:689 ℃/2024-10-10 16:08:09

catalogs
  • Introduction to Guava
  • Joiner
    • list to string
    • map to string
    • Handling nested collections
    • Handling null values
  • Splitter
    • string to list
    • string to map
    • multiple splitter
  • exports
  • coding

Introduction to Guava

Guava is an open source Java library developed by Google that provides a set of core features to enhance the standard library of Java.

It contains many useful tools and collection classes that make Java development more efficient and code more concise and easy to maintain.

  • 1. Set of toolsImmutable Collections: Guava provides immutable collections (e.g. ImmutableList, ImmutableSet, ImmutableMap) that prevent accidental modification of a collection.Multiset, Multimap, BiMap: These collection types support more complex scenarios, such as allowing duplicate elements (Multiset), mapping a key to multiple values (Multimap), and bi-directional mapping (BiMap). Examples include allowing duplicate elements (Multiset), mapping a key to multiple values (Multimap), and bi-directional mapping (BiMap).

  • 2. (computing) cacheGuava provides a simple cache implementation that allows developers to cache data in memory to improve application performance. Caches can be easily created using CacheBuilder and support expiration policies and maximum size settings. ,

  • 3. concurrency tool, Guava includes tools for concurrent programming, such as ListenableFuture, which extends Java Future to allow registration of callbacks to handle asynchronous results.

  • 4. string processing (computing)The Strings utility class is provided for string manipulation and handling, such as null checking, concatenating strings, and so on.

  • 5. IO toolsGuava includes support for input and output, providing the Files and ByteStreams classes to simplify file read/write and byte stream operations.

  • 6. Hashing and CodingGuava provides powerful hash functions and encoding tools , support for generating MD5, SHA-1 and other hash values , and Base64 encoding and decoding .

  • 7. realmThe Range class allows the definition of a set of consecutive values, which is useful for working with ranges of values or time ranges.

  • 8. graphical data structureGuava also supports graphical data structures (Graph), which facilitate the representation of node and edge relationships, and are suitable for applications such as network and path analysis.

  • 9. PreconditionsThe Preconditions class is provided to simplify parameter validation and checking and to help developers quickly check input conditions at the beginning of a method.

  • 10. Extending the Java APIGuava also extends some of the Java Standard Library APIs, such as the Optional class, to handle values that may be null, thus avoiding NullPointerException.

Joiner

Converting Collections to String with Joiner

list to string


/**
 * utilization joiner commander-in-chief (military) list Convert to String
 */
private static void joinerTest1() {
    List<String> names = ("r", "a", "m", "b", "l", "e");
    String result = (",").join(names);
    (result);
}


  • on : used to specify the string separator

map to string


/**
 * Converting a map to a string using joiner
 */
private static void joinerTest2() {
    Map<String, String> map = ().
    ("name", "ramble");
    ("tag", "technology");
    String result = (" , ").withKeyValueSeparator(" = ")
            .join(map);
    (result);
}


  • withKeyValueSeparator: Used to specify the key and value separator.

Handling nested collections


/**
 * utilization joiner nested list Convert to String
 */
private static void joinerTest3() {
    List <ArrayList <String >> nested = (
            ("spring", "banana", "orange"),
            ("cat", "dog", "bird"),
            ("John", "Jane", "Adam"));
    ("nested set=" + (nested));
    String result = (";").join((nested,
            new Function<List<String>, String>() {
                @Override
                public String apply(List<String> input) {
                    return ("-").join(input);
                }
            }));
    (result);
}


Handling null values


/**
 * Handling of null values when using joiners.
 * Use skipNulls() to ignore null values.
 * Use useForNull() to replace the null value with the specified string.
 * Note: skipNulls() and useForNull() cannot be used together.
 */
private static void joinerTest4() {
    List<String> names = ("John", null, "Jane", "Adam", "Tom");
    String result = (",")
            // Ignore nulls
            // .skipNulls()
            // Replace nulls with the specified string
            .useForNull("I'm a null value")
            .join(names); // replace the null value with the specified string.
    (result);
}


  • Ignoring null values with skipNulls()
  • Use useForNull() to replace the null value with the specified string
  • Note: skipNulls() and useForNull() cannot be used at the same time.

Splitter

Splitting a String into a Collection with Splitter

string to list


/**
 * utilization splitter Converts a string to list
 */
private static void splitterTest1() {
    Input string = "apple - banana - orange";
    List<String> result = ("-")
            // Used to remove spaces before and after
            .trimResults()
            .splitToList(input);
    ((result));
}


  • trimResults: used to remove spaces before and after an element.

string to map


/**
 * utilization splitter Converts a string to map
 */
private static void splitterTest2() {
    String input = "John=first,Adam=second";
    Map<String, String> result = (",")
            .withKeyValueSeparator("=")
            .split(input);
    ((result));
}


multiple splitter


/**
 * utilization splitter Converts a string to list,utilization多个分隔符
 */
private static void splitterTest3() {
    String input = ",,orange,,,.cml-";
    List<String> result = ("[.,-]")
            // Ignore empty strings
            .omitEmptyStrings()
            .splitToList(input);
    ((result));
}


  • omitEmptyStrings: used to ignore empty strings

exports

The above sample code outputs the results:


r,a,m,b,l,e
name = ramble , tag = technology
Nested sets = [["spring", "banana", "orange"],["cat", "dog", "bird"],["John", "Jane", "Adam"]]
spring-banana-orange;cat-dog-bird;John-Jane-Adam
John, I'm null. Jane, Adam, Tom.
["apple", "banana", "orange"]
{"john": "first", "adam": "second"}
["apple", "banana", "orange", "cml"]

coding

/naylor_personal/ramble-spring-boot/tree/master/guava