I have two lists and I want to return a result in the following way:
- the result should contain elements that are in list one and list two
- output should be same order as per first list
Input :
val first = listOf(1, 2, 3, 4, 5,7,9,15,11)
val second = listOf(2, 15 , 4,3, 11)
Output:
val output = listOf(2,3,4,15,11)
Please help me to learn how to get common values in both lists in order of list first
in Kotlin.
CodePudding user response:
You can do
val output = first.filter { second.contains(it) }
CodePudding user response:
What you are looking for is the intersection of the two lists:
val output = first.intersect(second)
As pointed out by @Ivo the result is a Set
which can be turned into a list with output.toList()
. However, since the result is a set, it contains no duplicates, e.g. if first
is listOf(1,2,3,1,2,3)
and second
is listOf(2,4,2,4)
, the result will be equal to setOf(2)
.
If this is not acceptable, the solution of @Ivo should be used instead.