alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Java example source code file (FoldWithinPartitionFunction.java)

This example Java source code file (FoldWithinPartitionFunction.java) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Learn more about this Java project at its project page.

Java - Java tags/keywords

accumulator, arraylist, atomiclong, counter, exception, foldwithinpartitionfunction, function2, iterator, list, override, util

The FoldWithinPartitionFunction.java Java example source code

package org.deeplearning4j.spark.text.functions;

import org.apache.spark.Accumulator;
import org.apache.spark.api.java.function.Function2;
import org.deeplearning4j.berkeley.Counter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author jeffreytang
 */
public class FoldWithinPartitionFunction implements Function2<Integer, Iterator> {

    public FoldWithinPartitionFunction(Accumulator<Counter maxPartitionAcc) {
        this.maxPerPartitionAcc = maxPartitionAcc;
    }

    private Accumulator<Counter maxPerPartitionAcc;


    @Override
    public Iterator<AtomicLong> call(Integer ind, Iterator partition) throws Exception {

        List<AtomicLong> foldedItemList = new ArrayList() {{ add(new AtomicLong(0L)); }};

        // Recurrent state implementation of cum sum
        int foldedItemListSize = 1;
        while (partition.hasNext()) {
            long curPartitionItem = partition.next().get();
            int lastFoldedIndex = foldedItemListSize - 1;
            long lastFoldedItem = foldedItemList.get(lastFoldedIndex).get();
            AtomicLong sumLastCurrent = new AtomicLong(curPartitionItem + lastFoldedItem);

            foldedItemList.set(lastFoldedIndex, sumLastCurrent);
            foldedItemList.add(sumLastCurrent);
            foldedItemListSize += 1;
        }

        // Update Accumulator
        long maxFoldedItem = foldedItemList.remove(foldedItemListSize - 1).get();
        Counter<Integer> partitionIndex2maxItemCounter = new Counter<>();
        partitionIndex2maxItemCounter.incrementCount(ind, maxFoldedItem);
        maxPerPartitionAcc.add(partitionIndex2maxItemCounter);

        return foldedItemList.iterator();
    }
}

Other Java examples (source code examples)

Here is a short list of links related to this Java FoldWithinPartitionFunction.java source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.