繁体   English   中英

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

[英]How to iterate over every n elements with java?

我有一个名为calculate的方法,完成时间太长。 所以我决定将我的信息列表对象部分地发送给这个方法。 我如何迭代每个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;
    }
}

听起来你想要做的是对Map<String, Long> info实例所代表的数据实现一种批处理 然后,您可以将这些批次的生成器创建为Stream :这与Stream.flatMap(...)系列方法相反,但具有讽刺意味的是, 似乎没有任何惯用的功能方式这样做 ,所以你可能必须自己以强制方式创建批次 - 例如:

private static <T> Stream<Stream<T>> createBatchStreams(final Iterator<T> iter, final int maxBatchSize) {
    final Stream.Builder<Stream<T>> resultBuilder = Stream.builder();
    {
        // NOTE: This logic could also be encapsulated in a Collector class
        // in order to make it less imperative style
        Stream.Builder<T> currentBatchBuilder = Stream.builder();
        int currentBatchSize = 0;

        while (iter.hasNext()) {
            final T next = iter.next();
            if (currentBatchSize == maxBatchSize) {
                resultBuilder.add(currentBatchBuilder.build());
                // Start building a new batch
                currentBatchBuilder = Stream.builder();
                currentBatchSize = 0;
            }
            currentBatchBuilder.add(next);
            currentBatchSize++;
        }
        // Check if there is a non-empty Stream to add (e.g. if there was a
        // final batch which was smaller than the others)
        if (currentBatchSize > 0) {
            resultBuilder.add(currentBatchBuilder.build());
        }
    }
    return resultBuilder.build();
}

使用此方法,您可以创建一组批量的地图数据生成器,然后可以将其提供给您的calculate(...)函数(尽管签名略有不同):

public static void main(final String[] args) {
    final Map<String, Long> info = LongStream.range(0, 10).boxed()
            .collect(Collectors.toMap(value -> "key" + value, Function.identity())); // Test data
    final Stream<Stream<Entry<String, Long>>> batches = createBatchStreams(info.entrySet().iterator(), 5);
    batches.forEach(batch -> {
        calculate(batch);
        // Do some other stuff after processing each batch
    });
}

private static boolean calculate(final Stream<Entry<String, Long>> info) {
    // Some calculations
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM