Splitter limit() method | Guava | Java
Last Updated :
31 Jan, 2019
The method limit(int limit) returns a splitter that behaves equivalently to this splitter but stops splitting after it reaches the limit. The limit defines the maximum number of items returned by the iterator, or the maximum size of the list returned by splitToList(java.lang.CharSequence).
For example, Splitter.on(‘, ‘).limit(3).split(“a, b, c, d”) returns an iterable containing [“a”, “b”, “c, d”].
Syntax:
public Splitter limit(int limit)
Parameters: This method takes limit as parameter which is the maximum number of items to be returned.
Return Value: This method returns a splitter with the desired configuration.
Example 1:
import com.google.common.base.Splitter;
import java.util.List;
class GFG {
public static void main(String[] args)
{
String str = "geeks, . for, .Hey., "
+ "geeks, ., noida, ., classes" ;
System.out.println( "When Limit is 3 : " );
Iterable<String> result = Splitter.on( ',' )
.limit( 3 )
.trimResults()
.split(str);
for (String temp : result) {
System.out.println(temp);
}
System.out.println( "\n\nWhen Limit is 4 : " );
Iterable<String> result1 = Splitter.on( ',' )
.limit( 4 )
.trimResults()
.split(str);
for (String temp : result1) {
System.out.println(temp);
}
}
}
|
Output:
When Limit is 3 :
geeks
. for
.Hey., geeks, ., noida, ., classes
When Limit is 4 :
geeks
. for
.Hey.
geeks, ., noida, ., classes
Example 2:
import com.google.common.base.Splitter;
import java.util.List;
class GFG {
public static void main(String[] args)
{
String str = "Learn$,,Data $ structures"
+ " 123$ to be $ best Coder.." ;
System.out.println( "When Limit is 2 : " );
Iterable<String> result = Splitter.on( '$' )
.limit( 2 )
.trimResults()
.split(str);
for (String temp : result) {
System.out.println(temp);
}
System.out.println( "\n\nWhen Limit is 4 : " );
Iterable<String> result1 = Splitter.on( '$' )
.limit( 4 )
.trimResults()
.split(str);
for (String temp : result1) {
System.out.println(temp);
}
}
}
|
Output:
When Limit is 2 :
Learn,,Data $ structures 123$ to be $ best Coder..
When Limit is 4 :
Learn,,Data
structures 123
to be $ best Coder..
Note:
- When omitting empty strings, the omitted strings do not count. Hence, Splitter.on(‘, ‘).limit(3).omitEmptyStrings().split(“a,,, b,,, c, d”) returns an iterable containing [“a”, “b”, “c, d”].
- When trim is requested, all entries are trimmed, including the last. Hence Splitter.on(‘, ‘).limit(3).trimResults().split(” a, b, c, d “) results in [“a”, “b”, “c, d”].
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...