Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 816
toucheqt Avatar asked Jun 17 '16 18:06

toucheqt


People also ask

How do you check if a collection contains an element?

contains() method check if a collection contains a given object, using the . equals() method to perform the comparison. Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ?

How to check if list contains an item Scala?

contains() function in Scala is used to check if a list contains the specific element sent as a parameter. list. contains() returns true if the list contains that element. Otherwise, it returns false .

What are the few collections in Scala?

There are two types of collections in Scala – mutable and immutable.


2 Answers

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
like image 104
WestCoastProjects Avatar answered Oct 11 '22 12:10

WestCoastProjects


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
like image 37
Peter Neyens Avatar answered Oct 11 '22 12:10

Peter Neyens