user3322141
user3322141

Reputation: 158

How to count elements from list if specific key present in list using scala?

I have following list structure -

"disks" : [ 
    {
        "name" : "A",
        "memberNo" :1 
    }, 
{
        "name" : "B",
        "memberNo" :2 
    },
{
        "name" : "C",
        "memberNo" :3 
    },
{
        "name" : "D",

    }
]

I have many elements in list and want to check for 'memberNo', if it exists I want count of from list elements.

e.g. here count will be 3

How do I check if key exists and get count of elements from list using scala??

Upvotes: 1

Views: 116

Answers (2)

elm
elm

Reputation: 20435

In a similar fashion as in @SergeyLagutin answer, consider this case class

case class Disk (name: String, memberNo: Option[Int] = None)

where missing memberNo are defaulted with None; and this list,

val disks = List( Disk("A", Some(1)), 
                  Disk("B", Some(2)),
                  Disk("C", Some(3)),
                  Disk("D"))

Then with flatMap we can filter out those disks with some memberNo, as follows,

disks.flatMap(_.memberNo)
res: List[Int] = List(1, 2, 3)

Namely, for the counting,

disks.flatMap(_.memberNo).size
res: Int = 3

Likewise, with a for comprehension,

for (d <- disks ; m <- d.memberNo) yield m
res: List[Int] = List(1, 2, 3)

Upvotes: 2

Sergii Lagutin
Sergii Lagutin

Reputation: 10681

First create class to represent your input data

case class Disk (name : String, memberNo : String)

Next load data from repository (or other datasource)

val disks: List[Disk] = ...

And finally count

disks.count(d => Option(d.memberNo).isDefined)

Upvotes: 4

Related Questions