Kotlin: How can I print only string elements from this list !? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Kotlin: How can I print only string elements from this list !?

My code : fun main(){ var myList = {"ABC", 42, 100.0, "xyz", "123"} // Now what should I do to print String elements !? } I tried with lambda function, but couldn't find a way.

6th Nov 2020, 4:56 AM
kev_coding
kev_coding - avatar
3 Answers
0
Gotcha, I just only need to add this : myList.filterIsInstance<String>().forEach{ Println (it) }
6th Nov 2020, 6:13 AM
kev_coding
kev_coding - avatar
+ 4
First of all u need to to use listOf() function, to create the list u want to create in ur question, and then u can easily use filter and forEach method to do this thing, see: val myList = listOf("ABC", 42, ...) // this will make List of type of class Any // Now im checking if the element is String or not, and then printing it myList.filter{ it is String }.forEach{ println(it) } Hope this helps u. Keep coding in kotlin!!☺👍
18th Nov 2020, 8:26 AM
MOHAN👨🏻‍💻
MOHAN👨🏻‍💻 - avatar
+ 3
You could do this as well. for(element in myList){ if(element is String){ println(element); } }
6th Nov 2020, 6:16 AM
Avinesh
Avinesh - avatar