// FormatGroceryItemsMap Example // Run this example on the Kotlin Playground Webpage at // https://play.kotlinlang.org // Remove or comment out example outputs before running. //********************************* // Example A. Load GroceryItem data // into MutableMap collection. //********************************* // Grocery items entered from TextField // and read into these variables. var desc = "Peanuts" var code = "24680" var price = "2.99" // Create mutable map. In an app, // is a state variable. var groceryMap = mutableMapOf( ) // Load grocery items into map. var groceryItem = "($desc;$code;$price)" groceryMap.put(code, groceryItem) // Add another item. desc = "Cashews" code = "32435" price = "2.99" groceryItem = "($desc;$code;$price)" // Use code for the map key. groceryMap.put(code, groceryItem) // Look at current items in the map. println(groceryMap.toString( )) println( ) // Output: [(Peanuts;24680;2.99), (Cashews;32435;2.99)] // Grocery items in this format can be stored // in a file. //********************************* // Example B. Format GroceryItem data // from MutableMap to display string, for // example in a Text element. //********************************* // Sample values of items in mutableMap: {24680=(Peanuts;24680;2.99), 32435=(Cashews;32435;2.99)} // Select map item with key 32435 var key = "32435" var display = "" if (key in groceryMap) { // groceryMap.getValue(key) is needed instead // of groceryMap[key] to insure a String return // value instead of String? var item = groceryMap.getValue(key) println(item) var item2 = item.removeSurrounding("(", ")") println(item2) var itemArray = item2.split(";") display += "Key: $key\n" + "Description: ${itemArray[0]}\n" + "Code: ${itemArray[1]}\n" + "Price: ${itemArray[2]}\n\n" } println(display) // Output: Description: Peanuts Code: 24680 Price: 2.99 Description: Cashews Code: 32435 Price: 2.99 //**************************************** // Example C. Load list toString formatted // formatted data from file back into list. //**************************************** var formatted = "[(Peanuts;24680;2.99), (Cashews;32435;2.99)]" groceryMap.clear( ) val formattedArray = formatted.removeSurrounding("[", "]") val groceryArray = formattedArray.split(",") println(groceryArray) for(item in groceryArray) { val key = item.split(";")[1].trim( ); groceryMap.put(key, item) } print(groceryMap) // Output: {24680=(Peanuts;24680;2.99), 32435=(Cashews;32435;2.99)}