简体   繁体   中英

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

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM