Is there an efficient way to set all values in a Trove map to zero?

404 views Asked by At

Is there an efficient way to set all values in a Trove map to zero?

Right now I am doing this:

    public static class NcZeroD implements TDoubleProcedure{
        public TDoubleDoubleHashMap map;

        @Override
        public boolean execute(double k) {
            map.put(k, 0);
            return true;
        }   
    }

    static NcZeroD ncZeroD=new NcZeroD();   

    public static void zero(TDoubleDoubleHashMap map){
        ncZeroD.map=map;
        map.forEachKey(ncZeroD);
    }

but it seems sort of messy.

1

There are 1 answers

0
Matt Ball On BEST ANSWER

It's at least a little cleaner if you use transformValues() instead of forEachKey():

private static final TDoubleFunction TO_ZERO = new TDoubleFunction() {
    @Override
    public double execute(double value) {
        return 0;
    }
};

public static void zero(TDoubleDoubleHashMap map) {
    map.transformValues(TO_ZERO);
}

I don't think you're going to see a more efficient solution — at some point, something has to iterate over all the values.