V Sri Sandeep
V Sri Sandeep

Reputation: 15

Unable to write map for the function

I have a data like this:

val timeArr = Array("09:00:00|09:30:00", "10:00:00|11:00:00", "12:00:00|15:00:00","10:00:01|13:23:55")

I would like my output in the following manner

(‘09:00:00’, ‘S’)
(‘09:30:00’, ‘E’)
(‘10:00:00’, ‘S’)
(‘10:00:01’, ‘S’)
(‘11:00:00’, ‘E’)
(‘12:00:00’, ‘S’)
(‘13:23:55’, ‘E’)
(‘15:00:00’, ‘E’)

having S for start time and E for end time.

I tried various ways using map, but it didn't work.

Upvotes: 0

Views: 64

Answers (4)

jwvh
jwvh

Reputation: 51271

As a "code golf" challenge, I wanted to see how short I could make it.

timeArr.flatMap(x => Array((x take 8, 'S'), (x drop 9, 'E')))

Upvotes: 1

Carlos Verdes
Carlos Verdes

Reputation: 3147

First you need to create a map to create tuples (start, end) and then what you miss is to create a flatMap.

Try something like this:

val result = timeArr.map(_.split("\\|"))
  .flatMap(t => (t(0), 'S') :: (t(1), 'E') :: Nil)

Some explanation:

map(_.split("\\|")

This split the string into an Array of String, so each element of the original collection now has an Array of String.

So... now you have an Array of Arrays... but you need a simple Array. For this type of problem is when you need to use flatMap:

flatMap(t => (t(0), 'S') :: (t(1), 'E') :: Nil)

Upvotes: 0

Brian
Brian

Reputation: 20285

Building off of @mfirry answer I think this gives what you want.

The split("|") yields an Array[Array[String]] which is a little clumsy to work with. Using flatMap and case Array(a, b, _*) makes working with the inner arrays easier to get the desired output. Lastly, you sort on the first element (time) of the tuple.

scala> timeArr.map(_.split("\\|")).flatMap { case Array(a, b, _*) => Array((a, 'S'), (b, 'E'))}.sortBy(t => t._1)

res150: Array[(String, Char)] = 
 Array(
   (09:00:00,S),
   (09:30:00,E),
   (10:00:00,S),
   (10:00:01,S),
   (11:00:00,E),
   (12:00:00,S),
   (13:23:55,E),
   (15:00:00,E)
 )

Upvotes: 4

mfirry
mfirry

Reputation: 3692

This should work:

for {
  a <- timeArr.map(_.split("\\|"))
  b <- a.zipWithIndex.map{ case (e, i) => if(i == 0) { (e,'S') } else (e, 'E') }
} yield b

or a funny one-liner:

timeArr.map(_.split("\\|")).flatMap { case Array(a, b, _*) => Array((a, 'S'), (b, 'E')) }

Upvotes: 3

Related Questions