Single iteration => Multiple output collections from Java to Scala -
i'm trying convert java code scala code. challenge ensure converted scala code doesn't end doing inefficient when compared original java one. e.g. when trying convert following code:
class person { string name; integer age; character gender; } public class testjava { public static void main(string[] args) { final list<person> persons = new arraylist<>(); final list<person> males = new arraylist<>(); final list<person> anames = new arraylist<>(); final list<person> seniors = new arraylist<>(); (final person p: persons) { if (p.gender == 'm') { males.add(p); } if (p.age >= 60) { seniors.add(p); } if (p.name.startswith("a")) { anames.add(p); } } } }
since java relies on mutation, code looks logical. but, want convert scala equivalent without looping on collection multiple times (3 times in case).
i can of course use mutable list
scala library , achieve same thing done java wondering if possible generate multiple collections given sequence/collection in functional/scala way without iterating on collection n
times n
criteria count. in advance!
one purely functional , immutable way have generic function separates collections buckets, predicate:
case class person(name: string, age: int, gender: string) def bucketsbypredicate(people: seq[person], predicates: seq[person => boolean]) = { people.foldleft(predicates.map(predicate => (predicate, list.empty[person]) )) { case (predicates, person) => predicates.map { case (predicate, members) => (predicate, if(predicate(person)) person :: members else members) } }.map(_._2) }
then example usage be:
val olderthan60 = (p: person) => p.age >= 60 val male = (p: person) => p.gender == "m" val seq(olderthan60people, malepeople) = bucketsbypredicate(people, seq(olderthan60, male))
Comments
Post a Comment