Thursday 13 July 2023

Using FindFirst in an Odd Way?

So I have a list, and I'm pretty sure it's either empty or contains one element.

So I was thinking too hard, and fabricated something like this:

public Optional<Item> getItem() {
  return items.isEmpty() ? Optional.empty() : Optional.of(items.get(0)));
}

And then I thought: "What am I thinking!?" and used the stream API instead:

public Optional<Item> getItem() {
  return items.stream().findFirst();
}

There.

Seems easy enough.

No comments:

Post a Comment