2

In Kotlin or Java, I have a list of items that have an ID property. This list is generated based on another list. Now I get a List of mentioned list items and I want to select all items in the parent list, selecting by ID equality.
Is there a more elegant way than just iterating the parent lost for each derived item? Thank you :)

Comments
  • 1
    I don't think I understand. Can you give a small example?
  • 1
    Figured it out, I was thinking too complicated.

    I have List l2 = l1.map(...)

    Now I received a subset of l2 elements and wanted the corresponding l1 elements. Like:
    l1.filter(el -> subset.any(s -> s.id == el.id))
  • 1
    A mapping would be more performant, and depending on the domain, make more sense.
    (Referring to the data structure not the method).
  • 1
    I.E:
    Assuming:
    list1: List<T : ObjectWithID>
    list2: List<Integer> // if IDs are ints
    Then:
    val idToObj = list1.map { it.id to it }.toMap()
    val selected = list2.map { idToObject.get(it) }
  • 1
    Oh, really. Looks like a nice solution. I'll look into it. Thanks :)
Add Comment