📜  Splitter withKeyValueSeparator(char separator) 方法 |番石榴 |Java

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

Splitter withKeyValueSeparator(char separator) 方法 |番石榴 |Java

Guava 的 Splitter 类的withKeyValueSeparator(char separator)方法接受强制参数分隔符,并使用此分隔符将条目拆分为键和值。

句法:

参数:该方法接受参数分隔符,并使用此分隔符将条目拆分为键和值。

返回值:该方法返回一个MapSplitter ,它基于此拆分器拆分条目。

注意:我们将成对的分隔符传递给此方法。 on() 方法接收键和值对之间的分隔符。

下面的例子说明了 Guava 的 Splitter 类的 withKeyValueSeparator() 方法的实现:

示例 1:

// Java code to show implementation of
// withKeyValueSeparator(char separator) method
// of Guava's Splitter Class
  
import com.google.common.base.Splitter;
import java.util.Map;
import java.util.Map.Entry;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
        // This String contains key-value pairs.
        String value
            = "Data Structures=Coding,Sports=Football,Capital=Delhi";
  
        // Using Splitter to parse key-value separators.
        // This returns a MapSplitter which splits
        // entries based on this splitter, and splits
        // entries into keys and
        // values using the specified separator.
        Map
            mp
            = Splitter.on(',')
                  .withKeyValueSeparator('=')
                  .split(value);
  
        // Looping over entries stored in map mp.
        for (Entry entry : mp.entrySet()) {
  
            // Displaying key and value pairs
            System.out.println(entry.getKey() + " -> "
                               + entry.getValue());
        }
    }
}
输出:
Data Structures -> Coding
Sports -> Football
Capital -> Delhi

示例 2:

// Java code to show implementation of
// withKeyValueSeparator(char separator) method
// of Guava's Splitter Class
  
import com.google.common.base.Splitter;
import java.util.Map;
import java.util.Map.Entry;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
        // This String contains key-value pairs.
        String value
            = "First=I.Second=II.Third=III.Fourth=IV";
  
        // Using Splitter to parse key-value separators.
        // This returns a MapSplitter which splits
        // entries based on this splitter, and splits
        // entries into keys and values
        // using the specified separator.
        Map
            mp
            = Splitter.on('.')
                  .withKeyValueSeparator('=')
                  .split(value);
  
        // Looping over entries stored in map mp.
        for (Entry entry : mp.entrySet()) {
  
            // Displaying key and value pairs
            System.out.println(entry.getKey() + " -> "
                               + entry.getValue());
        }
    }
}
输出:
First -> I
Second -> II
Third -> III
Fourth -> IV