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 passedpredicate
.objectList.filterNot { it is object2 || it is object3 }
This would return a list after removing all elements from
objectList
that would be of typeobject2
orobject3
. -
answered 2022-05-04 11:01
Stepan Kulagin
Your second variant is workable, just set
!
beforeis
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 aList<Number>
and callfilterIsInstance<Int>()
on it, the return value is the more specificList<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 usefilter
orfilterNot
instead with a lambda that uses anis
or!is
check. -
answered 2022-05-04 14:55
k314159
The
filterIsInstance
function and theis
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)
do you know?
how many words do you know