ADVERTISEMENT
ADVERTISEMENT

Kotlin program to get the list equivalent of the Pair

Learn how to get the list equivalent of the Pair using toList() function?
Submitted by IncludeHelp, on April 02, 2022

In the below given examples, we will create Pair using the constructor and demonstrate how to get the list equivalent of the Pair using toList() function?

toList() function:

The toList() function returns a list representation of the Pair including its first and second values i.e., it converts this pair into a list.

Syntax:

fun <T> Pair<T, T>.toList(): List<T>

Consider the below examples –

Example 1:

fun main() {
	// Creates a new instance of the Pair
	val pair1 = Pair(10, 20)

	// Converts this pair into a list
	val list1: List<Any> = pair1.toList()
	println("list1 : "+list1)

	// Creates a new instance of the Pair
	val pair2 = Pair("Alvin Alexander", 35)	

	// Converts this pair into a list
	val list2: List<Any> = pair2.toList()
	println("list2 : "+list2)
}

Output:

list1 : [10, 20]
list2 : [Alvin Alexander, 35]

Example 2:

fun main() {
	// Creates a new instance of the Pair
	// Here, first value is the string and 
	// the second value is the list of strings
	val pair1 = Pair("Developers", listOf("Alvin", "Alex", "David"))

	// Converts this pair into a list
	val list1: List<Any> = pair1.toList()
	println("list1 : "+list1)

	// Creates a new instance of the Pair
	// Here, first value is the list of strings (names)
	// the second value is the list of integers (ages)
	val pair2 = Pair(listOf("Alvin", "Alex", "David"), listOf(20, 25, 30))

	// Converts this pair into a list
	val list2: List<Any> = pair2.toList()
	println("list2 : "+list2)
}

Output:

list1 : [Developers, [Alvin, Alex, David]]
list2 : [[Alvin, Alex, David], [20, 25, 30]]

Kotlin Pair Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.