Search code examples
javacastinglambdaj

Lambdaj class casting


i have some code like this:

List<ClassB> back = new ArrayList<ClassB>();
for( ClassA classA : getClassAs() )
{
    if( classA instanceof ClassB )
    {
        back.add((ClassB) classA);
    }
}

ClassB extends ClassA

Is there some smart way to do this in lambdaj? I know there is the IsInstanceOf Matcher but i have to do the cast by 'hand'.

thanks in advance

mojoo


Solution

  • This is not that efficient but may provide some direction:

    Your original list was named as "back" in your post:

    1.Filter "back" elements into a new list by type (List containing only objects of type B)

    List bList = Lambda.filter(org.hamcrest.Matchers.instanceOf(B.class),back);
    

    2.Using a converter object convert filtered object list bList to List

    List<B> list = Lambda.convert(bList,new Converter<Object, B>() {
        public B convert(Object from) {
            return (B) from;
            }
        });