3

So I am writing a method that returns List<V>. However, the list that I've made in the method is List<Vertex<V>>. I was wondering if there's some way to convert List<Vertex<V>> to List<V> to match the return type other than just removing the "Vertex" part. Thanks!

1
  • You could write custom code to getV() from Vertex then add V to different List<V> but you can not cast it unless Vertex<V> extends V which in your case I don't think it does. Commented Nov 25, 2014 at 20:14

2 Answers 2

3

If you are using java 8 there's an easy way to map a collection to a different type of collections simple write:

list.stream().map(vertex -> vertex.get()).collect(Collectors.toList());     

vertex.get() should be any code that takes a Vertex<V> and converts it to V.

Sign up to request clarification or add additional context in comments.

1 Comment

You can also do map(Vertex::get) instead of map(vertex -> vertex.get()).
1

Short answer is no, you can't solve this with "casting" alone. V is not the same as Vertex<V> so you need a way to extract the V object from each of your Vertex<V> objects.

Comments

Your Answer

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