Reputation: 1308
Let's say I have classes:
class SomeClass(
val name: String
)
data class MyClass (
val setValues: Set<SomeClass>,
val intValue: Int
)
Then I create set like this:
val someClass1 = SomeClass("a")
val someClass2 = SomeClass("b")
val someClass3 = SomeClass("c")
val someClass4 = SomeClass("d")
val someClass5 = SomeClass("e")
val someClass6 = SomeClass("f")
val val1 = MyClass(setOf(someClass1, someClass2, someClass3), 1)
val val2 = MyClass(setOf(someClass1, someClass4, someClass5), 2)
val val3 = MyClass(setOf(someClass4, someClass5, someClass6), 3)
val setOfMyClass = setOf(val1, val2, val3)
and I want to do some operations on this set setOfMyClass
like
val result = set. ...
and as a result get mapping like this:
someClass1 to 1
someClass2 to 1
someClass3 to 1
someClass1 to 2
someClass4 to 2
someClass5 to 2
someClass4 to 3
someClass5 to 3
someClass6 to 3
it probably should be some kind of list.
Upvotes: 1
Views: 76
Reputation: 1026
You have a Set<MyClass>
, which each contains a Set<SomeClass>
. To map a collection of collections into a single collection, usually flatMap
is the solution. In your example, combining flatMap
on the outer set and map
on the inner set gives you a list of mapped pairs.
This gives you a List<Pair<SomeClass, Int>>
- which is probably what you want?
val result = setOfMyClass.flatMap { myObject ->
myObject.setValues.map { it to myObject.intValue }
}
Or if you want it as a Map<SomeClass, Int>
, simply do the same as above and:
result.toMap()
Upvotes: 2
Reputation: 1490
I'm not sure if I understand your question, but I'll give it a try.
Let's say SomeClass was Int and you want to compute intValue + x for every element x from setValues.
Int this case you'd do myClassObject.setValues.map{Pair(it, myClassObject.intValue)}
and receive a list of the results. The result is a list and not a set, because some results could appear multiple times (as the mapping does not need to be injective), and the multiplicity of elements is lost in a set.
Upvotes: 0
Reputation: 91
If i'm understand your question, the solution will be: setValues.associateWith { intValue } that will return Map<SomeClass, Int>
Upvotes: 0