Unzip the sequence of case classes with two fields

Let's say I have a case class MyCaseClass with two fields in the constructor and a sequence of values ​​for this class case, sequence .

How to unpack a sequence ?

+4
source share
2 answers

If fields a and b , I just write

 (sequence map (_.a), sequence map (_.b)) 

OK, you go through the sequence twice, but traversing the list is so cheap, I would say it is faster than using Option.get.

edit: after Rex’s comment, I couldn’t resist running the test; results below ...

 times in ms for 100 traversals of 10000 elem collection, L = List, A = Array, V = Vector // Java 6 // Java 7 sequence.unzip{case MyCaseClass(a,b) => (a,b)} //L 173 A 101 V 87 //L 27 A 29 V 21 sequence.unzip{MyCaseClass.unapply(_).get} //L 194 A 116 V 100 //L 35 A 32 V 25 (sequence map (_.a), sequence map (_.b)) //L 177 A 70 V 86 //L 34 A 20 V 23 

Your results may vary depending on the processor, memory, JRE version, collection size, moon phase, etc.

+3
source

Class classes do not distribute Product2, Product3, etc., so simple unpacking does not work.

It does:

 sequence.unzip { MyCaseClass.unapply(_).get } 
+2
source

Source: https://habr.com/ru/post/1492329/


All Articles