'Filtering array list

I have a class which I want to use, to filter my array according to driver. Driver is hardcoded just to try and eliminate possibilities of why the code is not working. I have tried a lot of different methods none seem to working. I get the error IndexOutOfBoundsException: Index: 1, Size: 0 after my line of println(driverList[3].DELNO).

   private fun datafilter(tripsheetlist: ArrayList<DataModel>, driver: String): List<DataModel> {
   println("driver in datafilter subclass")
   println(driver)
   
   println("tripsheetlist[3].DELNO")
   println(tripsheetlist[3].DELNO)
   
   var driverList: List<DataModel> = tripsheetlist

   //   var driverList : ArrayList<DataModel> = tripsheetlist.filter { s -> s == driver }
   var i = 0
   while (  i != tripsheetlist.size){
        driverList = tripsheetlist.takeWhile { tripsheetlist[i].DRIVER == "JIM" }
       i++
   }
 
   println("driverList[3].DELNO")
   println(driverList[3].DELNO)

       return driverList
   }

Below is DataModel

class DataModel(
   var TRIPSHEETNO: Int,
   var WONUMBER: String,
   var DELNO: Int,
   var CUSTOMER: String,
   var DRIVER: String,
   var WEIGHT: Double,
   var state: DataState = DataState.Unselected
   )

After the filter I have seen it returns as an List and not ArrayList. I have established that this does not affect my data.

Thank you for all suggestions.

Solution :

private fun datafilter(tripsheetlist: ArrayList<DataModel>, driver: String): ArrayList<DataModel> {
   return ArrayList(tripsheetlist.filter { it.DRIVER == driver }) }


Solution 1:[1]

IndexOutOfBoundsException: Index: 1 Size: 0 might be coming from println(driverList[3].DELNO) line, after you use takeWhile on the list as you are trying to access the index that is not available in the list.

Here

tripsheetlist.takeWhile { tripsheetlist[i].DRIVER == "JIM" }

in takeWhile you've are comparing the DRIVER of only first item, so it would either return emptyList when the first item's DRIVER won't be JIM or the full list when the first item's DRIVER value would be JIM.

You should not use takeWhile for your use case, as it would only return the items at the beginning of the list which match your given condition. So, if your first item's DRIVER is not JIM it would return an emptyList and if your first two item's DRIVER is JIM, it would return those two only and won't check for remaining items.

You should use filter and your method can be refactored like this

private fun datafilter(tripsheetlist: ArrayList<DataModel>, driver: String): List<DataModel> {
    return tripsheetlist.filter { it.DRIVER == driver }
}

After the filter I have seen it returns as an List and not ArrayList

filter and takeWhile return a list, so if you want an ArrayList. You have to cast it as ArrayList like this

ArrayList(tripsheetlist)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Praveen