https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

andodeki

04/02/2022, 1:39 AM
Hey guys: I to access individual items in ItemList but i am getting below as output how can i list only "Name1" and "Name2" from "defaultItems"
[Item(int=1, item=Category1, ItemList={Name=[]})]
null
Copy code
data class Item(
    	var int: Int,
        var item: String,
        var ItemList: Map<String, List<Item>>
    )
    var defaultcategory = listOf(
        Item(1, "Category1", mapOf("Name" to listOf<Item>()))
    )
    var defaultItems = listOf(
        Item(1, "Item1",mapOf("Name1" to defaultcategory)),
        Item(2, "Item2",mapOf("Name2" to defaultcategory))
    )
    
    defaultItems.forEachIndexed { index, element ->
    	print(element.ItemList["Name1"])
        print("\n")
    }
s

Stephan Schroeder

04/02/2022, 9:07 AM
I changed a few things in your code:
ItemList
should be lowercase, immutable
val
by default instead of
var
, a trailing comma for the itemList parameter and a unique result filter operation with
first(predicate).let{...}
to only work on the first item that contains the key
Name1
in its
itemList
(use
filter(predicate).forEach{...}
if you want to iterate all the items that fullfill this condition.
Copy code
fun main() {
    defaultItems.first{item->item.itemList.contains("Name1")}.let{itemWithName1->
        print(itemWithName1.itemList["Name1"])
	}
    
}

data class Item(
    val int: Int,
    val item: String,
    val itemList: Map<String, List<Item>>,
)

val defaultcategory = listOf(
    Item(1, "Category1", mapOf("Name" to listOf<Item>()))
)
val defaultItems = listOf(
    Item(1, "Item1",mapOf("Name1" to defaultcategory)),
    Item(2, "Item2",mapOf("Name2" to defaultcategory))
)