2017-01-21 5 views
0

私は、リストの要素を表示し、リストからそれらの項目を削除する必要がある次のコードを持っています。私はkotlinのフィルタ対マップを見てきましたが、解決策を見つける運がありません。KotlinのMutableListから要素を削除するには

var mutableList: MutableList<Object> = myImmutableList.toMutableList() 
for (x in mutableList.indices) 
{ 
    val tile = row!!.getChildAt(x % 4) 
    val label = tile.findViewById(android.R.id.text1) as TextView 
    label.text = mutableList[x].name 
    val icon = tile.findViewById(android.R.id.icon) as ImageView 
    picasso.load(mutableList[x].icon).into(icon) 
} 

答えて

0

あなたは全体のリストを反復処理しているため、最も簡単な方法は、すべての項目を処理した後MutableListclear methodを呼び出すことであろう。

mutableList.clear() 

他のオプションが指定されたインデックスの要素を削除するために与えられた要素やremoveAtを削除する方法removeである可能性があります。どちらも再びMutableListクラスのメソッドです。実際には、このようになります。

val list = listOf("a", "b", "c") 
val mutableList = list.toMutableList() 
for (i in list.indices) { 
    println(i) 
    println(list[i]) 
    mutableList.removeAt(0) 
} 
0

最初の不変のコレクションをマップしてフィルタリングするだけの理由はありますか? "List#toMutableList()"を呼び出すと既にコピーを作成しているので、それを避けることで達成しようとしていることはよくわかりません。

val unprocessedItems = myImmutableList.asSequence().mapIndexed { index, item -> 
    // If this item's position is a multiple of four, we can process it 
    // The let extension method allows us to run a block and return a value 
    // We can use this and null-safe access + the elvis operator to map our values 
    row?.getChildAt(index % 4)?.let { 
     val label = it.findViewById(android.R.id.text1) as TextView 

     label.text = item.name 
     val icon = it.findViewById(android.R.id.icon) as ImageView 

     picasso.load(item.icon).into(icon) 

     // Since it's processed, let's remove it from the list 
     null 
    } ?: item // If we weren't able to process it, leave it in the list 
}.filterNotNull().toList() 

もう一度、これで何が起こっているのかよく分かりません。より詳細なアプローチがあると思います。