3

I know it sounds dumb, but I really need it. I'm 100% positive about only allowing SubClass into the arraylist. No other subclass of SuperClass is in that arraylist.

How can I do this?

    Map<String, List<Nodo>> map = ((Cast to ArrayList<NodoMoore> here)nodos).stream().
collect(Collectors.groupingBy(Nodo::getSalida));

My class implements an interface that makes me use Nodo instead of NodoMoore, but the getSalida method is not a Nodo method, only a NodoMoore method.

2
  • Can you show us a few skeleton class definitions that would help us replicate what you're seeing? Also, which class is implementing the interface? Commented Feb 22, 2016 at 7:19
  • 2
    Can you map first, eg map a Nodo -> a NodoMoore with a cast? Commented Feb 22, 2016 at 7:21

2 Answers 2

8

If you are sure that nodos contains only instances of NodoMoore, you can map the Nodo instances to NodoMoore instances with a cast :

Map<String, List<NodoMoore>> map = 
    nodos.stream()
         .map(n->(NodoMoore)n)
         .collect(Collectors.groupingBy(NodoMoore::getSalida));

I assumed that NodoMoore is a sub-class of Nodo.

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

5 Comments

Hello, DaoWen's answer has the output I want but this is also a very useful answer.
A in my opinion slightly more elegant solutiin would be to use nodos.stream().map(NodoMoore.class::cast).collect(Collectors.groupingBy(NodoMoore::getSalida)), because it's better readable.
Hello, I'm new to this "::" thing. Why is it more elegant?
NodoMoore.class::cast is equal to p -> NodoMoore.class.cast(p). Using the ::-operator, you are implicitly either filling the parameters of the method or, if the method is non-static but supplied without an instance, giving the instance the method should run on. E.g. FooFactory::createFrom vs. Foo::toString.
Ups, i got drifted slightly away from your question. It's more elegant, because it's more readable, even for non-Java geeks.
6

Rather than using a method handle (Nodo::getSalida), you can use a lambda and do the cast there instead:

Map<String, List<Nodo>> map = nodos.stream()
    .collect(Collectors.groupingBy(x->((NodoMoore)x).getSalida());

3 Comments

Amazing, I had no idea I could do this. Thanks!
Note that this answer and Eran's answer have different return types. You'd pick one approach or the other based on your desired return type.
This was the desired output. I couldn't work with List<NodoMoore> because of the interface.

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.