Reputation: 7665
I want to know if there is a quicker and/or more elegant way to achieve this with Java 8. I would like to have a string no longer than a max length (say 4 character max)
input "" -> ""
input null -> null
input abc -> abc
input abcde -> abcd
some function (string s){
if(s==null)
return null;
if(s.length()>4)
return s.substring(1,4);
return s;
}
Upvotes: 3
Views: 5420
Reputation: 311073
If the string is not null
, you can always take a substring between 0
and the minimum between 4
and the length of the string. Couple this with Java 8's Optional
, and you can do this in single statement:
private static String noMoreThanFour(String str) {
return Optional.ofNullable(str)
.map(s -> s.substring(0, Math.min(4, s.length())))
.orElse(null);
}
Upvotes: 2
Reputation: 32507
1 less return statement keeping if-else structure
if(s==null || s.length()<=4){
return s;
}else return s.substring(0,4);
another stem would be to use conditional expression, but it wont be more readable
return (s==null || s.length()<=4)? s:s.substring(0,4)
Upvotes: 2
Reputation: 29837
If you don't mind pulling in an external dependency, Apache Commons StringUtils is full of handy helper methods that do exactly this kind of thing, including a null/length safe SubString.
I personally find with pure Java projects it is almost always beneficial to make use of Apache Commons for the myriad of helpers.
The above said, your code is easily readable, so I wouldn't go out of your way to change it.
Upvotes: 4