Correct use of if condition with in map in scala

时间:2017-12-18 04:56:16

标签: scala

I have two lists such that:

var pop=(List((1,3),(2,5)), List((3,7)(4,7)))
var list=List(4,3)

What I want is:

List(List(4, List((1,3),(2,5))), List(3,List((3,7),(4,7))))

I used two maps with one if condition i.e.:

pop.map(y=>(list.map(x=>if(list.indexOf(x)==pop.indexOf(y)){(x,y)})))

but the result is:

List(List((4,List((1,3),(2,5))),()), List((),(3, List((3,7),(4,7)))))

I want to get rid of these empty elements i.e. in above statement I have ().

2 个答案:

答案 0 :(得分:1)

You can simply do the following to achieve what your require

list.map(x => List(x, pop(list.indexOf(x))))

You should have output as

List(List(4, List((1,3), (2,5))), List(3, List((3,7), (4,7))))

You don't need if condition in the method that you are following and simply do the following

pop.map(y=> List(list(pop.indexOf(y)), y))

答案 1 :(得分:0)

By using indexOf, you might introduce some Runtime Exceptions. You are better of doing a Zip like this:

val (listAFromTuple, listBFromTuple) = (List((1,3),(2,5)), List((3,7)(4,7)))
val list = List(4,3)

list.zip(Seq(listAFromTuple, listBFromTuple))

The result will then be:

List((4,List((1,3), (2,5))), (3,List((3,7), (4,7))))

And the resulting type is:

List[(Int, List[(Int, Int)])]

If your tuple is bigger instead of just 2 elements, you could probably first convert the tuple as a List and then zip:

yourListTuple.productIterator.toList