Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I filter an ArrayList in Kotlin so I only have elements which match my condition?

I have an array:

var month: List<String> = arrayListOf("January", "February", "March") 

I have to filter the list so I am left with only "January".

like image 639
Nitt Avatar asked May 21 '17 15:05

Nitt


People also ask

How do I filter an array in Kotlin?

If you want to use element positions in the filter, use filterIndexed() . It takes a predicate with two arguments: the index and the value of an element. To filter collections by negative conditions, use filterNot() . It returns a list of elements for which the predicate yields false .

How do you access the ArrayList elements in Kotlin?

Kotlin arrayListOf() Example 4 - get()The get() function of arrayListOf() is used to retrieve the element present at specified index. For example: fun main(args: Array<String>){ val list: ArrayList<String> = arrayListOf<String>()


1 Answers

You can use this code to filter out January from array, by using this code

var month: List<String> = arrayListOf("January", "February", "March") // to get the result as list var monthList: List<String> = month.filter { s -> s == "January" }  // to get a string var selectedMonth: String = month.filter { s -> s == "January" }.single() 
like image 61
Nithinlal Avatar answered Sep 23 '22 02:09

Nithinlal