AndroidBites | Union, Intersect, Subtract in Kotlin

android Aug 02, 2020

small snippets on how you can perform union, intersection & subtraction on list!

“awesomeandroid”

TLDR : Snippet says it all 😉

Disclaimer : All the assets used as background belongs to respective companies I don't promote them as my own, they are just used to make code relatable and attractive.


Union, Intersect and Subtract are function present in Kotlin's standard collection api, they all return Set type and preserve the element iteration order of the first array, and since they all are infix they don't need ( , ), . tokens. I have added `List` operations that you would perform to get the similar results for comparison.

They are just small example I will highly recommend for looking up in docs for detailed explanation!, Now then 👁️ on the code 💻👇

Union : [Docs]

Returns a set containing all distinct elements from both of the list.

val listOfItem1:List<Int> = listOf(1,2,3,4)
val listOfItem2:List<Int> = listOf(4,5,6,7)

val resultA:List<Int> = (listOfItem1 + listOfItem2).distinct()
//output: [1, 2, 3, 4, 5, 6, 7]
			//vs
val resultB: Set<Int> = listOfItem1 union listOfItem2 
//output: [1, 2, 3, 4, 5, 6, 7]
val resultC: Set<Int> = listOfItem2 union listOfItem1 
//output: [4, 5, 6, 7, 1, 2, 3]
Kotlin | union example

Intersect : [Docs]

Returns a set containing all elements that are contained by both of the list.

val listOfItem1:List<Int> = listOf(1,2,3,4,5)
val listOfItem2:List<Int> = listOf(4,5,6,7)

val resultA:List<Int> = listOfItem1.filter{listOfItem2.contains(it)}
// output: [4, 5]
			//vs
val resultB:Set<Int> = listOfItem1 intersect listOfItem2 
//output: [4, 5]
Kotlin | intersection example

Subtract : [Docs]

Returns a set containing all elements that are contained by this list and not contained by the other list.

val listOfItem1:List<Int> = listOf(1,2,3,4) 
val listOfItem2:List<Int> = listOf(4,5,6,7)

val resultA:List<Int> = listOfItem1.filter{!listOfItem2.contains(it)}
// output : [1,2,3]
	
    //vs

val resultA:Set<Int> = listOfItem1 subtract listOfItem2 
// output : [1,2,3]
Kotlin | Subtract example

That's all fokes! , these are the basic operations that can be performed on the list and are always handy to know! see ya in next snippet 💻 Happy Hacking!


Enjoying the Post?

a clap is much appreciated if you enjoyed. No sign up or cost associated :)

If you want to support my content do consider dropping a tip/coffee/donation💰


P.S discover more such operations and functions from official docs :

kotlin.collections - Kotlin Programming Language


Chetan gupta

Hi there! call me Ch8n, I'm a mobile technology enthusiast! love Android #kotlinAlltheWay, CodingMantra: #cleanCoder #TDD #SOLID #designpatterns

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.