gpt4 book ai didi

java - 如何用java迭代每n个元素?

转载 作者:太空宇宙 更新时间:2023-11-04 11:56:10 24 4
gpt4 key购买 nike

我有一个名为计算的方法,它需要很长时间才能完成。所以我决定将我的信息列表对象部分发送到此方法。如何迭代每 n 个元素?

public static void main(String [] args){
Map<String, Long> info....; //my info Map

//I want to call method like
for(int i = 0; i<info.size(); i+=5)
calculate(info.submap(i,i+5));
}


public static boolean calculate(Map<String, Long> info){
//Some calculations

}

最佳答案

您可以使用以下代码

class SomeClass {

private final int BUFFER_SIZE = 5;

public static void main(String[] args) {
Map<String, Long> info = new HashMap<>();

LongStream.range(0, 30).boxed().forEach(i -> info.put("key" + i, i)); // for test

IntStream.range(0, info.size() / BUFFER_SIZE)
.boxed()
.parallel()
.map(i -> Arrays.copyOfRange(info.keySet().toArray(), BUFFER_SIZE * i, BUFFER_SIZE * (i + 1)))
.map(Arrays::asList)
.map(keys -> info.entrySet().stream()
.filter(x -> keys.contains(x.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)))
.forEach(SomeClass::calculate);
}

public static boolean calculate(Map<String, Long> info) {
System.out.println("calculation for " + info.toString());
return true;
}
}

关于java - 如何用java迭代每n个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41379056/

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