Skip to content

Optional support for Joiner #3581

Open
Open
@gebezs

Description

Summary

Avoiding null is a base principle in Guava. However the lack of Optional support in Joiner forces developers to use orElse(null) if they want to skip empty() values.

Optional<String> a = Optional.empty();
Optional<String> b = Optional.of("b");
Optional<String> c = Optional.empty();
Optional<Integer> d = Optional.empty();
Optional<Integer> e = Optional.of(5);
String result = Joiner.on(", ")
  .skipNulls()
  .join(a.orElse(null), b.orElse(null), c.orElse("c"), d.orElse(null), e.orElse(null));
assertThat(result)
  .isEqualTo("b, c, 5");

Expected behavior

It would be great if Guava's Joiner could support Optional values.

Optional<String> a = Optional.empty();
Optional<String> b = Optional.of("b");
Optional<String> c = Optional.empty();
Optional<Integer> d = Optional.empty();
Optional<Integer> e = Optional.of(5);
String result = Joiner.on(", ")
  .skipNotPresents()
  .join(a, b, c.orElse("c"), d, e);
assertThat(result)
  .isEqualTo("b, c, 5");

Rationale

I think that

Joiner.on(", ")
  .skipNotPresents()
  .join(a, b, c.orElse("c"), d, e);

is much clearer than

String result = Joiner.on(", ")
  .skipNulls()
  .join(a.orElse(null), b.orElse(null), c.orElse("c"), d.orElse(null), e.orElse(null));

Also this method would further push developers to avoid nulls.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions