1

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??

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Note that case classes are fantastic to represent json data models, especially when integrated with Jackson. Take a look at a similar question where I gave a code sample that uses Jackson: stackoverflow.com/a/26494306/1028765
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.