How to check if collection contains any element from other collection in Scala?

12,956

Solution 1

You can use a combination of exists(p: T => Boolean):Boolean and contains(elem: A1):Boolean :

val a = List(1,2,3,4,5,6,7)
val b = List(11,22,33,44,55,6)

a.exists(b.contains) // true

Solution 2

Intersect

val a = Seq(1,2,3) ; val b = Seq(2,4,5)
a.intersect(b)
res0: Seq[Int] = List(2)

// to include the test:
a.intersect(b).nonEmpty  // credit @Lukasz

Solution 3

Using disjoint() from the standard Java Collections utilities can determine if two collections contain any common members. If the collections are not disjoint, then they contain at least one common element.

Internally, Collections.disjoint() checks if either collection is a Set and optimizes accordingly.

import collection.JavaConverters._

val a = List(1,2,3,4,5,6,7)
val b = List(11,22,33,44,55,6)

!java.util.Collections.disjoint(a.asJava, b.asJava)  // true

Although this is still converting the Scala collection to a Java collection. On the plus side, the extra apache commons library isn't needed.

Share:
12,956
toucheqt
Author by

toucheqt

Updated on June 03, 2022

Comments

  • toucheqt
    toucheqt almost 2 years

    Title says it all, what is the best practice for finding out if collection contains any element of other collection?

    In java I would execute it like this

    CollectionUtils.containsAny(a, b)
    

    using common apache collection utils, where variables a/b are collections.

    How to implement this behavior in scala? Or is there library like CollectionUtils from above?

    I dont want to use the common-apache library because i would have to convert scala collection to java collection.

  • Alexander Aleksandrovič Klimov
    Alexander Aleksandrovič Klimov almost 8 years
    Not sure why it got a downvote. It's the obvious answer
  • Łukasz
    Łukasz almost 8 years
    It could look cleaner as a.intersect(b).nonEmpty.
  • pedrofurla
    pedrofurla almost 8 years
    The obvious answer is the other one, @TheArchetypalPaul. Anyways, I didn't downvote, just didn't vote.
  • Alexander Aleksandrovič Klimov
    Alexander Aleksandrovič Klimov almost 8 years
    Since the question is actually "do the two arrays have any elements in common" I still feel intersect of the obvious answer. It certainly didn't need a down vote. Imo obviously
  • WestCoastProjects
    WestCoastProjects almost 8 years
    @Łukasz Thx for the nonEmpty (vs !isEmpty)
  • conny
    conny almost 6 years
    That makes sense... but I'd argue it doesn't make for much readability 😳
  • conny
    conny almost 6 years
    Isn't it wasteful to have to create an intersection just to check whether it is nonEmpty? I think that is why people vote for the other solution.