Xorty
Xorty

Reputation: 18861

Java 8: Building initials from nullable first name and last name

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

Answers (3)

erickson
erickson

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

Jesper
Jesper

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

JB Nizet
JB Nizet

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

Related Questions