V Sri Sandeep V Sri Sandeep - 3 months ago 25
Scala Question

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’)

for start time and
for end time.

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


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:


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)