1

I have this line

List<Integer> someListWithLongName = someMapWithLongName.containsKey(someObjectWithLongName.get()) 
    ? someMapWithLongName.get(someObjectWithLongName.get()) 
    : Collections.emptyList();

That I wanted to change to make it a bit more readable, so I chose:

List<Integer> someListWithLongName = Optional.of(someMapWithLongName.get(someObjectWithLongName.get())
    .orElse(Collections.emptyList())

But I was told that the purpose of Optional is different. However, I'm failing to see why.
Is it really so? why?

CCC
  • 2,642
  • 7
  • 40
  • 62

1 Answers1

3

Some people will have different views on this but a good practice is to always use something the way it was intended.

see this answer for consequences of misusing the Optional<T> type.

instead of your current solution, a better solution hinted by @JB Nizet would be using Map::getOrDefault available as of JDK8.

List<Integer> result = map.getOrDefault(key, Collections.emptyList());
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126