Find the common elements between two lists of names.

← Collections and Data Structures · Ref: Q1163

Filter one list by membership in the other:

  common <- cat teamA
    | filter by isInTeamB
    | collect as List of String

Use a dynamic function capturing the second list and checking 'is in'.

See Q1101 for 'is in'. See Q1136 for collect as.

Example

defines module qa.collections.listintersection

  defines function

    InListCheck as pure abstract
      -> name as String
      <- rtn as Boolean?

  defines program

    ListIntersectionDemo()
      stdout <- Stdout()

      teamA <- ["Alice", "Bob", "Charlie", "Diana"]
      teamB <- ["Charlie", "Eve", "Alice", "Frank"]

      //Dynamic function capturing teamB for the membership check
      isInTeamB <- (teamB) extends InListCheck as pure function
        rtn: name is in teamB

      //Filter teamA to only those also in teamB
      common <- cat teamA | filter by isInTeamB | collect as List of String
      stdout.println(`Common members: ${common}`)

Common mistakes

E50060 — EK9 List has no retainAll() method; compute an intersection with a filter pipeline using 'is in'. See ek9 -h E50060 for details.

Incorrect:

common <- teamA.retainAll(teamB)

Correct:

common <- cat teamA | filter by isInTeamB | collect as List of String
Other ways to ask this
  • Write code to compute the intersection of two lists
  • I have teamA and teamB lists and need the members in both
  • Given two lists, filter one to only items that appear in the other
  • In Python I'd use set(a) & set(b). Write the EK9 list intersection

Coming from another language?

Python: set(a) & set(b) or [x for x in a if x in b]. Java: a.stream().filter(b::contains). EK9: cat a | filter by capturedCheck | collect.

Keywords: common, lists, filter, is in, both, intersection