Splitter withKeyValueSeparator(char separator) method | Guava | Java
Last Updated :
31 Jan, 2019
The withKeyValueSeparator(char separator) method of Guava’s Splitter Class accepts a mandatory parameter separator and splits entries into keys and values using this separator.
Syntax:
public Splitter.MapSplitter withKeyValueSeparator(char separator)
Parameters: The method accepts a parameter separator and splits entries into keys and values using this separator.
Return Value: The method returns a MapSplitter which splits entries based on this splitter.
Note: We pass the separator within pairs to this method. The on() method receives the separator between pairs of keys and values.
Below examples illustrate the implementation of withKeyValueSeparator() method of Guava’s Splitter class:
Example 1:
import com.google.common.base.Splitter;
import java.util.Map;
import java.util.Map.Entry;
class GFG {
public static void main(String[] args)
{
String value
= "Data Structures=Coding,Sports=Football,Capital=Delhi" ;
Map<String, String>
mp
= Splitter.on( ',' )
.withKeyValueSeparator( '=' )
.split(value);
for (Entry<String, String> entry : mp.entrySet()) {
System.out.println(entry.getKey() + " -> "
+ entry.getValue());
}
}
}
|
Output:
Data Structures -> Coding
Sports -> Football
Capital -> Delhi
Example 2:
import com.google.common.base.Splitter;
import java.util.Map;
import java.util.Map.Entry;
class GFG {
public static void main(String[] args)
{
String value
= "First=I.Second=II.Third=III.Fourth=IV" ;
Map<String, String>
mp
= Splitter.on( '.' )
.withKeyValueSeparator( '=' )
.split(value);
for (Entry<String, String> entry : mp.entrySet()) {
System.out.println(entry.getKey() + " -> "
+ entry.getValue());
}
}
}
|
Output:
First -> I
Second -> II
Third -> III
Fourth -> IV
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...