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?

2

1 Answer 1

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.