Vikas Pandya
Vikas Pandya

Reputation: 1988

apply multiple filter conditions and produce only one element from a list

say for e.g.

scala> case class Entitlement(read: Boolean, edit: Boolean, create: Boolean, delete: Boolean)
defined class Entitlement

scala> List (Entitlement(read= true, edit = true, create= false, delete =false),Entitlement(read= true, edit = false, create= false, delete =false),Entitlement(read= true, edit = true, create= false, delete =true))
res0: List[Entitlement] = List(Entitlement(true,true,false,false), 
Entitlement(true,false,false,false), Entitlement(true,true,false,true))

Is there a way to create ONE and ONLY one Entitlement(true,true,false,true) with a single pass of a List res0 such that it'll go thru the list and if read=true found that's the final read privilege else default value for read=false - if edit=true found that's the final edit privilege else default value for edit=false and so on. in this toy example create=false in all of the Entitlement elements in the List why final result will be

Entitlement(true,true,false,true)

Upvotes: 0

Views: 137

Answers (2)

Jegan
Jegan

Reputation: 1751

You can achieve the same with reduce too. Below is an example. The advantage here is that you do not need to pass an initial value and it is more intuitive.

res0.reduce((e1, e2) => Entitlement(e1.read | e2.read, e1.edit | e2.edit, e1.create | e2.create, e1.delete | e2.delete))

Upvotes: 0

marstran
marstran

Reputation: 27971

You can fold your list and or together the corresponding values of the Entitlements. You start with an Entitlement with all values set to false.

res0.fold(Entitlement(false, false, false, false))((e1, e2) => 
    Entitlement(
        e1.read || e2.read, 
        e1.edit || e2.edit, 
        e1.create || e.create,
        e1.delete || e2.delete))

Upvotes: 3

Related Questions