How can you determine whilst iterating in an Array if the actual object satisfies a specific criteria compared to all other objects within that same Array ?
Let me explain my question using an example.
Lets assume we have an array containing 5 objects of type Person.
data class Person(val name: String, val age: Int)
Now I'd like to be able to determine in that array containing 5 persons the oldest person in case there are multiple occurences of the name.
So in the example
val pers1 = Person("Jake", "22")
val pers2 = Person("Oliver", "25")
val pers3 = Person("Mark", "35")
val pers4 = Person("John", "35")
val pers5 = Person("Mark", "55")
val persons = arrayOf(emp1, emp2, emp1, emp3, emp4, emp5)
So having this array I'd like to be able whilst iterating through the objects to determine if the Person I'm evaluating in that moment is the oldest with that name in the whole array so that I cant act on it...
In Pseudocode something like
for(i in persons.indices){
person with non-unique name AND oldest in this array -> do something
}
CodePudding user response:
I think it's easier to work with ArrayLists than Array and then this is what you might want:
val pers1 = Person("Jake", 22)
val pers2 = Person("Oliver", 25)
val pers3 = Person("Mark", 35)
val pers4 = Person("John", 35)
val pers5 = Person("Mark", 55)
val persons = arrayListOf(pers1, pers2, pers3, pers4, pers5)
persons.groupBy { it.name }.entries.map { it.value.maxByOrNull { it.age }}.forEach {
//here only the oldest persons of a name come
}
CodePudding user response:
Generally speaking, it is not possible to check against all items in the array at the same time. We would need to perform another iteration over all items, making our solution very inefficient (O(n^2)
).
However, such cases can be very often implemented in much more efficient way. For example, your case can be implemented by grouping the list into a map:
persons.groupingBy { it.name }
.fold(0) { acc, person -> maxOf(acc, person.age) }
In simple words, it searches for the maximum age per each name. It results with:
{Jake=22, Oliver=25, Mark=55, John=35}
I believe it should be close to O(n)
.