Home > Software engineering >  How to sort listOfItem based on condition in Kotlin
How to sort listOfItem based on condition in Kotlin

Time:02-18

This is my given code

var type1 listOf<Type> = 0 size;
var type2 listOf<Type> = {"Ait 45","Ait 46"}
var type3 listOf<Type> = {"Ait 47"}
var type4 listOf<Type> = 0
var type5 listOf<Type> = {"Ait 58","Ait 59"}

Using below code i am sorting it

val data = ArrayList<Product>()
        data.add(Product(it=1,type1))
        data.add(Product(it=2,type2))
        data.add(Product(it=3,type3))
        data.add(Product(it=4,type3))
        data.add(Product(it=5,type4))

data.sortedBy { it.type.get(0).value}

i am trying to sort based on type value but i am getting ArrayIndexoutBound exception because type1 and type4 having empty or null so i want to sort if such type of item should come at last based on inserted order please help me how to apply condition to check if type is empty or null i dont want sort those item simply i can keep at end of list .

CodePudding user response:

You're calling List<E>.get(index: Int): E which returns the element at the specified index in the list. By the way, as this is an operator fun you could as well use the shorthand syntax it.type[0].value, which is the exact same.

However, this won't fix your problem. If you're unsure that an element exists at the specified index, you should rather use a function that can cope with this, such as List<T>.getOrNull(index: Int): T?, which returns an element at the given index or null if the index is out of bounds of this list.

Thus, you might end up with something along the lines of:

data.sortedBy { it.type.getOrNull(0)?.value}

Note that sortedBy returns a list of all elements sorted according to natural sort order of the value returned by specified selector function.

If you want a custom sort order, you might want to take a look at sortedWith instead, which allows to define a custom Comparator.

  • Related