Filtering list based on instance type

I've a list of different objects extending from the same parent class. I want to remove only 2 objects from the list based on the instance type. I found filterInstanceOf() but it actually returns the object that matches this filter.

val objectList = listOf(object1, object2, object3, object4)

I want to do something like:

objectList.filterInstanceIsNot(object2).filterInstanceIsNot(object3)

or

objectList.filter { it is! object2 && it is! object3)

how can I do it?

4 answers

  • answered 2022-05-04 10:58 Praveen

    There's also a filterNot method for the list, which returns a list after removing all the elements that match the passed predicate.

    objectList.filterNot { 
        it is object2 || it is object3
    }
        
    

    This would return a list after removing all elements from objectList that would be of type object2 or object3.

  • answered 2022-05-04 11:01 Stepan Kulagin

    Your second variant is workable, just set ! before is

    objectList.filter { it !is object2 && it !is object3)
    

  • answered 2022-05-04 13:20 Tenfour04

    The point of filterIsInstance is that it returns a List with a more specific type than the input Iterable you gave it. For example, if you have a List<Number> and call filterIsInstance<Int>() on it, the return value is the more specific List<Int>.

    If you are doing the reverse, there is no logical more specific type it can give you, so there is no reason for the standard library to include filterIsNotInstance. You can simply use filter or filterNot instead with a lambda that uses an is or !is check.

  • answered 2022-05-04 14:55 k314159

    The filterIsInstance function and the is keyword work on types, but what you're providing as arguments are instances. Therefore, I think you need something like this:

    objectList.filter { it::class != object2::class && it::class != object3::class)
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum