Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast from Optional<> to ArrayList<>

I have the following situation:

public ArrayList<A> getMethods(){
    return b.c.test();
}

So, my problem is that b.c.test() returns a value with Optional<A> as return type. But I need to return an ArrayList<A>.

So, I tried to cast it and rewrite it to :

public ArrayList<A> getMethods(){
    return (ArrayList<A>)b.c.test();
}

But Eclipse says that such a cast from Optional<A> to ArrayList<A> is not possible.

How can I solve this problem?

like image 608
user3097712 Avatar asked Jul 28 '15 22:07

user3097712


1 Answers

I am presuming your intended semantic is 'if the value is present return a list with a single item, otherwise return an empty list.' In that case I would suggest something like the following:

ArrayList<A> result = new ArrayList<>();
b.c.test().ifPresent(result::add);
return result;

However I would suggest your return type should be List<A> rather than ArrayList<A> as that gives you the opportunity to change the type of list without changing the callers. It would also allow you to return Collections.EMPTY_LIST if the optional value is not present which is more efficient than creating an unnecessary ArrayList.

Update: there's now an easier option with Java 9:

b.c.test().stream().collect(Collectors.toList());

Update: and even easier option with Java 16:

b.c.test().stream().toList();
like image 83
sprinter Avatar answered Oct 20 '22 04:10

sprinter