Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter a List according to multiple contains

I want to filter a List, and I only want to keep a string if the string contains .jpg,.jpeg or .png:

scala>  var list = List[String]("a1.png","a2.amr","a3.png","a4.jpg","a5.jpeg","a6.mp4","a7.amr","a9.mov","a10.wmv")
list: List[String] = List(a1.png, a2.amr, a3.png, a4.jpg, a5.jpeg, a6.mp4, a7.amr, a9.mov, a10.wmv)

I am not finding that .contains will help me!

Required output:

List("a1.png","a3.png","a4.jpg","a5.jpeg")
like image 429
Govind Singh Avatar asked Nov 10 '14 11:11

Govind Singh


3 Answers

Use filter method.

list.filter( name => name.contains(pattern1) || name.contains(pattern2) )

If you have undefined amount of extentions:

val extensions = List("jpg", "png")
list.filter( p => extensions.exists(e => p.matches(s".*\\.$e$$")))
like image 169
Sergii Lagutin Avatar answered Nov 10 '22 02:11

Sergii Lagutin


Why not use filter() with an appropriate function performing your selection/predicate?

e.g.

list.filter(x => x.endsWith(".jpg") || x.endsWith(".jpeg")

etc.

like image 32
Brian Agnew Avatar answered Nov 10 '22 02:11

Brian Agnew


To select anything that contains one of an arbitrary number of extensions:

list.filter(p => extensions.exists(e => p.contains(e)))

Which is what @SergeyLagutin said above, but I thought I'd point out it doesn't need matches.

like image 3
thund Avatar answered Nov 10 '22 03:11

thund