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

时间:2016-12-29 11:44:41

标签: java java-8

我有一个名为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

}

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码

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;
    }
}

答案 1 :(得分:0)

听起来你想要做的是为你的Map<String, Long> info实例代表的数据实现一种batch processing。然后,您可以Stream为这些批次创建generator:这与Stream.flatMap(...)系列方法相反,但具有讽刺意味的是,there doesn't seem to be any idiomatic functional way of doing this等等您可能必须以强制方式自行创建批次 - 例如:

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
}