gpt4 book ai didi

java - 以更实用的方式对目录进行分组

转载 作者:行者123 更新时间:2023-11-29 05:23:22 25 4
gpt4 key购买 nike

有人可以告诉我如何将此 Scala 代码(Java 命令式方式)转换为更实用的方式吗?

它是按总共 4GB 的目录/文件将目录/文件分成 4 组,每组限制 1GB,将每个组添加到列表中。

object MyMapper {
def main(args: Array[String]) {
var map: Map[String, Long] = Map[String, Long]();
map += ("a" -> 5);
map += ("b" -> 5);
map += ("c" -> 3);
map += ("d" -> 2);
map += ("e" -> 4);
map += ("f" -> 2);
map += ("g" -> 1);

limitMapper(map)
}

def limitMapper(map: Map[String, Long]): Unit = {
var offset = 0L;

var result = Vector[Vector[String]]()
var list = Vector[String]()
val iterator: Iterator[(String, Long)] = map.toVector.iterator
val LIMIT: Int = 10
while (iterator.hasNext) {
val (path, size) = iterator.next()
println((path, size))

offset += size
if (offset > LIMIT) {
offset = size;
result = result :+ list
list = Vector[String]()
}

list = list :+ path
}

//add remaining paths
if (list.size > 0) {
result = result :+ list
list = Vector[String]()
}

println(result)
println(s"LIMIT = $LIMIT")


}
}


Output:
(e,4)
(f,2)
(a,5)
(b,5)
(g,1)
(c,3)
(d,2)
Vector(Vector(e, f), Vector(a, b), Vector(g, c, d))

最佳答案

我不确定这是否是最好的方法。但我会做类似的事情:

val map = ...
val limit = 1073741824L

val res = map.foldLeft(Vector(Vector[String]())){ case (result, (path, size)) =>
if(result.last.map(map(_)).sum + size > limit) {
result :+ Vector(path)
} else result.updated(result.size - 1, result.last :+ path)
}

关于java - 以更实用的方式对目录进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23750032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com