Reputation: 18861
Looking for a better way or existing library that'll allow more elegant way of constructing initials. Current thing I got seems a bit clumsy:
String first = Optional.ofNullable(person.getFirstName()).orElse("");
first = first.isEmpty() ? first : first.substring(0, 1);
String last = Optional.ofNullable(person.getLastName()).orElse("");
last = last.isEmpty() ? last : last.substring(0, 1);
return first + last;
Upvotes: 1
Views: 554
Reputation: 269657
final class NameUtils
{
static String initials(Person p)
{
Stream<String> s = Stream.of(p.getFirstName(), p.getLastName());
return s.filter(NameUtils::isValid).map(x -> x.substring(0, 1)).collect(Collectors.joining());
}
private static boolean isValid(String s)
{
return (s != null) && (s.length() > 0);
}
}
Upvotes: 1
Reputation: 206796
You can use map
:
String first = Optional.ofNullable(person.getFirstName())
.map(s -> s.substring(0, 1)).orElse("");
(Are you using Java 8's Optional
? That doesn't have fromNullable
and or
methods - it has ofNullable
and orElse
methods instead).
Using Google Guava's Optional
instead of Java 8's:
String first = Optional.fromNullable(person.getFirstName())
.transform(s -> s.substring(0, 1)).or("");
Upvotes: 3
Reputation: 691685
// extract common code to method to avoid duplication
private String getInitial(String s) {
return (s != null && !s.isEmpty()) ? s.substring(0, 1) : "";
}
private String getInitials(Person person) {
return getInitial(person.getFirstName()) + getInitial(person.getLastName());
}
Upvotes: 6