I have an array filled with mixed user Inventory objects.
the objects have an object.name attribute.
when I iterate through the array it will already be sorted by name.
if we looked at obj.name in the array it would have this structure
[ball,ball,monkey,monkey,sausage]
I would like to loop through the array.
get all elements with common name attribute and create a new array out of those elements.
any suggestions there? bonus points if we can name the array the object.name attribute. I am using Kotlin.
Here is the code/thoughts I have to start, any other suggestions are appreciated if this is not doable
private fun sortElements(){
val temp = userstuff[0].name //but what if they only have 1 of these names.. doesnt work
userstuff.forEach { element ->
if(temp == element.name)
we have another item with same name put in appropriate array
else{
new array
loop
}
CodePudding user response:
If I'm understanding your use case correctly, you should be able to do something like this:
private fun sortElements(input: List<Stuff>) = input.groupBy { it.name }
The idea here is that you take each element and put it into a Map
where the key is the name
value and the values are a List
of your objects.
To give an example here, let's say I have a data class
called Stuff
:
data class Stuff(
val name: String,
val otherField: Int,
)
and test data that looks like this:
val userStuff = listOf(
Stuff("ball", 242),
Stuff("ball", 11),
Stuff("monkey", 848),
Stuff("monkey", 455),
Stuff("sausage", 836),
)
Calling the function above would give a result like this (this would be a Map<String, Stuff>
, I just printed it out so you can see what's in there):
{
ball=[
Stuff(name=ball, otherField=242),
Stuff(name=ball, otherField=11)
],
monkey=[
Stuff(name=monkey, otherField=848),
Stuff(name=monkey, otherField=455)
],
sausage=[
Stuff(name=sausage, otherField=836)
]
}