如何通过迭代器分组而不将其转换为Scala中的列表? [英] How to groupBy an iterator without converting it to list in scala?

查看:49
本文介绍了如何通过迭代器分组而不将其转换为Scala中的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要在迭代器上使用groupBy,编译器将询问"value groupBy is not a member of Iterator[Int]".一种方法是将迭代器转换为我要避免的列表.我想做groupBy,使输入为Iterator[A],输出为Map[B, Iterator[A]].这样,仅当访问元素的该部分时才加载迭代器的该部分,而不将整个列表加载到内存中.我也知道可能的一组键,所以我可以说是否存在特定的键.

Suppose I want to groupBy on a iterator, compiler asks to "value groupBy is not a member of Iterator[Int]". One way would be to convert iterator to list which I want to avoid. I want to do the groupBy such that the input is Iterator[A] and output is Map[B, Iterator[A]]. Such that the part of the iterator is loaded only when that part of element is accessed and not loading the whole list into memory. I also know the possible set of keys, so I can say whether a particular key exists.

def groupBy(iter: Iterator[A], f: fun(A)->B): Map[B, Iterator[A]] = {
    .........
}

推荐答案

一种可能性是,您可以将Iterator转换为view,然后将groupBy as转换为

One possibility is, you can convert Iterator to view and then groupBy as,

iter.toTraversable.view.groupBy(_.whatever)

这篇关于如何通过迭代器分组而不将其转换为Scala中的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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