单次迭代=>从Java到Scala的多个输出集合 [英] Single iteration => Multiple output collections from Java to Scala

查看:107
本文介绍了单次迭代=>从Java到Scala的多个输出集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试将一些Java代码转换为Scala代码。面临的挑战是确保转换后的Scala代码与原始Java代码相比,最终不会产生非常低效的代码。对于例如在尝试转换以下代码时:

I'm currently trying to convert some Java code to Scala code. The challenge is to ensure that the converted Scala code doesn't end up doing something very inefficient when compared to the original Java one. For e.g. when trying to convert the 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<>();
        for (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);
            }            
        }
    }
}

自Java依赖于变异,这段代码看似合乎逻辑。 但是,现在我想将它转换为Scala等效的,而不是多次循环遍历该集合(在这种情况下为3次)。

Since Java relies on mutation, this code looks logical. But, now I want to convert this to its Scala equivalent without looping over the collection multiple times (3 times in this case).

我当然可以从Scala库中使用可变的 List 并实现与Java相同的操作但是想知道是否可以生成多个集合来自给定的序列/集合的函数/ Scala方式没有迭代集合 n n 是标准计数。在此先感谢!

I can of course use mutable List from the Scala library and achieve the same thing as done by Java but was wondering if it was possible to generate multiple collections from a given sequence/collection in a functional/Scala way without iterating over the collection for n times where n is the criteria count. Thanks in advance!

推荐答案

一种纯粹功能和不可变的方法是通过谓词将一个通用函数分隔成桶:

One purely functional and immutable way would be to have a generic function that separates collections into buckets, by 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 an example usage could be:

val olderThan60 = (p: Person) => p.age >= 60
val male = (p: Person) => p.gender == "m"
val Seq(olderThan60People, malePeople) = bucketsByPredicate(people, Seq(olderThan60, male))

这篇关于单次迭代=&gt;从Java到Scala的多个输出集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆