Home > OS >  How can I filter array of <Any> by its type -Kotlin?
How can I filter array of <Any> by its type -Kotlin?

Time:07-22

I have an array arrayOf<Any>("Apple",46,"287",574,"Peach","3","69",78,"Grape","423") and I need to sort it: firstly numbers suppose to go like "3",46,"69"... and then words by alphabet... So I am trying first to divide them on separate arrays by type and then some manipulation. Do you have advice of how to solve this problem?

CodePudding user response:

So just had to make some manipulation

val onlyNumbers = a.filterIsInstance<Int>()
val allStrings = a.filterIsInstance<String>().sorted()
val onlyStrings = mutableListOf<String>()
val listOfEditedNumbers = mutableListOf<Int>()
allStrings.forEach {
    try {
        val toInt = it.toInt()
        listOfEditedNumbers.add(toInt)
    } catch (e: java.lang.Exception){
        onlyStrings.add(it)
    }
}
val allNumbers = onlyNumbers.toList()   listOfEditedNumbers
val finalSortedNumberList = allNumbers.sorted()
val finalNumbersList = mutableListOf<Any>()
finalSortedNumberList.forEach {
    if (it in onlyNumbers) finalNumbersList.add(it)
    if (allStrings.contains(it.toString())) finalNumbersList.add(it.toString())
}
val finalTotalList = finalNumbersList   onlyStrings.sorted()

CodePudding user response:

You can try my solution


val a = arrayOf<Any>("Apple",46,"287",574,"Peach","3","69",78,"Grape","423")
 val numbers = mutableListOf<Int>()
   val strings = mutableListOf<String>()
   val stringNumber = mutableListOf<Int>()
   
   for(e in a){
       if(e is Int) numbers.add(e)
       if(e is String){
           if(e.toIntOrNull() == null){
               strings.add(e)
           } else {
               stringNumber.add(e.toInt())
           }
       }
   }
   
   val result = (numbers   stringNumber).sorted().map { value -> 
       // convert back to String
       stringNumber.find{ it == value }?.toString() ?: value
   }   strings.sorted() 
   
   println(result)

CodePudding user response:

You can sort the array using a custom comparator:

fun main() {
    println(
        arrayOf<Any>("Apple",46,"287",574,"Peach","3","69",78,"Grape","423")
            .sortedBy {
                if (it is Number || (it is String && it.toLongOrNull() != null))
                    1
                else
                    2
            }
    )
}

Output: [46, 287, 574, 3, 69, 78, 423, Apple, Peach, Grape]

  • Related