Package com.gs.collections.impl.bag.mutable.primitive

Source Code of com.gs.collections.impl.bag.mutable.primitive.IntHashBag

/*
* Copyright 2014 Goldman Sachs.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.gs.collections.impl.bag.mutable.primitive;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Arrays;
import java.util.NoSuchElementException;

import com.gs.collections.api.IntIterable;
import com.gs.collections.api.LazyIntIterable;
import com.gs.collections.api.bag.MutableBag;
import com.gs.collections.api.bag.primitive.IntBag;
import com.gs.collections.api.bag.primitive.ImmutableIntBag;
import com.gs.collections.api.bag.primitive.MutableIntBag;
import com.gs.collections.api.block.function.primitive.IntToObjectFunction;
import com.gs.collections.api.block.function.primitive.ObjectIntToObjectFunction;
import com.gs.collections.api.block.function.primitive.IntToIntFunction;
import com.gs.collections.api.block.predicate.primitive.IntPredicate;
import com.gs.collections.api.block.procedure.primitive.IntProcedure;
import com.gs.collections.api.block.procedure.primitive.IntIntProcedure;
import com.gs.collections.api.iterator.IntIterator;
import com.gs.collections.api.list.primitive.MutableIntList;
import com.gs.collections.api.set.primitive.IntSet;
import com.gs.collections.api.set.primitive.MutableIntSet;
import com.gs.collections.impl.Counter;
import com.gs.collections.impl.bag.mutable.HashBag;
import com.gs.collections.impl.block.factory.primitive.IntToIntFunctions;
import com.gs.collections.impl.factory.primitive.IntBags;
import com.gs.collections.impl.lazy.primitive.LazyIntIterableAdapter;
import com.gs.collections.impl.list.mutable.primitive.IntArrayList;
import com.gs.collections.impl.map.mutable.primitive.IntIntHashMap;
import com.gs.collections.impl.set.mutable.primitive.IntHashSet;
import net.jcip.annotations.NotThreadSafe;

/**
* IntHashBag is similar to {@link HashBag}, and is memory-optimized for int primitives.
* This file was automatically generated from template file primitiveHashBag.stg.
*
* @since 3.0.
*/
@NotThreadSafe
public final class IntHashBag implements MutableIntBag, Externalizable
{
    private static final long serialVersionUID = 1L;

    private IntIntHashMap items;
    private int size;

    public IntHashBag()
    {
        this.items = new IntIntHashMap();
    }

    public IntHashBag(int size)
    {
        this.items = new IntIntHashMap(size);
    }

    public IntHashBag(IntIterable iterable)
    {
        this();
        this.addAll(iterable);
    }

    public IntHashBag(IntHashBag bag)
    {
        this.items = new IntIntHashMap(bag.sizeDistinct());
        bag.forEachWithOccurrences(new IntIntProcedure()
        {
            public void value(int item, int occurrences)
            {
                IntHashBag.this.addOccurrences(item, occurrences);
            }
        });
    }

    public static IntHashBag newBag(int size)
    {
        return new IntHashBag(size);
    }

    public static IntHashBag newBagWith(int... source)
    {
        IntHashBag result = new IntHashBag();
        result.addAll(source);
        return result;
    }

    public static IntHashBag newBag(IntIterable source)
    {
        if (source instanceof IntHashBag)
        {
            return new IntHashBag((IntHashBag) source);
        }

        return new IntHashBag(source);
    }

    public static IntHashBag newBag(IntBag source)
    {
        final IntHashBag result = new IntHashBag();
        source.forEachWithOccurrences(new IntIntProcedure()
        {
            public void value(int each, int occurrences)
            {
                result.addOccurrences(each, occurrences);
            }
        });
        return result;
    }

    public boolean isEmpty()
    {
        return this.items.isEmpty();
    }

    public boolean notEmpty()
    {
        return this.items.notEmpty();
    }

    public int size()
    {
        return this.size;
    }

    public int sizeDistinct()
    {
        return this.items.size();
    }

    public void clear()
    {
        this.items.clear();
        this.size = 0;
    }

    public IntHashBag with(int element)
    {
        this.add(element);
        return this;
    }

    public IntHashBag with(int element1, int element2)
    {
        this.add(element1);
        this.add(element2);
        return this;
    }

    public IntHashBag with(int element1, int element2, int element3)
    {
        this.add(element1);
        this.add(element2);
        this.add(element3);
        return this;
    }

    public IntHashBag withAll(IntIterable iterable)
    {
        this.addAll(iterable);
        return this;
    }

    public IntHashBag without(int element)
    {
        this.remove(element);
        return this;
    }

    public IntHashBag withoutAll(IntIterable iterable)
    {
        this.removeAll(iterable);
        return this;
    }

    public boolean contains(int value)
    {
        return this.items.containsKey(value);
    }

    public boolean containsAll(int... source)
    {
        for (int each : source)
        {
            if (!this.items.containsKey(each))
            {
                return false;
            }
        }
        return true;
    }

    public boolean containsAll(IntIterable source)
    {
        return source.allSatisfy(new IntPredicate()
        {
            public boolean accept(int each)
            {
                return IntHashBag.this.contains(each);
            }
        });
    }

    public int occurrencesOf(int item)
    {
        return this.items.get(item);
    }

    public void forEachWithOccurrences(IntIntProcedure procedure)
    {
        this.items.forEachKeyValue(procedure);
    }

    public boolean add(int item)
    {
        this.items.updateValue(item, 0, IntToIntFunctions.increment());
        this.size++;
        return true;
    }

    public boolean remove(int item)
    {
        int newValue = this.items.updateValue(item, 0, IntToIntFunctions.decrement());
        if (newValue <= 0)
        {
            this.items.removeKey(item);
            if (newValue == 0)
            {
                this.size--;
            }
            return newValue == 0;
        }
        this.size--;
        return true;
    }

    public boolean addAll(int... source)
    {
        if (source.length == 0)
        {
            return false;
        }

        for (int each : source)
        {
            this.add(each);
        }
        return true;
    }

    public boolean addAll(IntIterable source)
    {
        if (source.isEmpty())
        {
            return false;
        }
        if (source instanceof IntBag)
        {
            IntBag otherBag = (IntBag) source;
            otherBag.forEachWithOccurrences(new IntIntProcedure()
            {
                public void value(int each, int occurrences)
                {
                    IntHashBag.this.addOccurrences(each, occurrences);
                }
            });
        }
        else
        {
            IntIterator iterator = source.intIterator();
            while (iterator.hasNext())
            {
                int each = iterator.next();
                this.add(each);
            }
        }
        return true;
    }

    public boolean removeAll(int... source)
    {
        if (source.length == 0)
        {
            return false;
        }
        int oldSize = this.size();
        for (int each : source)
        {
            int occurrences = this.items.removeKeyIfAbsent(each, 0);
            this.size -= occurrences;
        }
        return this.size() != oldSize;
    }

    public boolean removeAll(IntIterable source)
    {
        if (source.isEmpty())
        {
            return false;
        }
        int oldSize = this.size();
        if (source instanceof IntBag)
        {
            IntBag otherBag = (IntBag) source;
            otherBag.forEachWithOccurrences(new IntIntProcedure()
            {
                public void value(int each, int occurrences)
                {
                    int oldOccurrences = IntHashBag.this.items.removeKeyIfAbsent(each, 0);
                    IntHashBag.this.size -= oldOccurrences;
                }
            });
        }
        else
        {
            IntIterator iterator = source.intIterator();
            while (iterator.hasNext())
            {
                int each = iterator.next();
                int occurrences = this.items.removeKeyIfAbsent(each, 0);
                this.size -= occurrences;
            }
        }
        return this.size() != oldSize;
    }

    public boolean retainAll(IntIterable source)
    {
        int oldSize = this.size();
        final IntSet sourceSet = source instanceof IntSet ? (IntSet) source : source.toSet();
        IntHashBag retained = this.select(new IntPredicate()
        {
            public boolean accept(int key)
            {
                return sourceSet.contains(key);
            }
        });
        if (retained.size() != oldSize)
        {
            this.items = retained.items;
            this.size = retained.size;
            return true;
        }
        return false;
    }

    public boolean retainAll(int... source)
    {
        return this.retainAll(IntHashSet.newSetWith(source));
    }

    public void addOccurrences(int item, final int occurrences)
    {
        if (occurrences < 0)
        {
            throw new IllegalArgumentException("Cannot add a negative number of occurrences");
        }
        if (occurrences > 0)
        {
            this.items.updateValue(item, 0, new IntToIntFunction()
            {
                public int valueOf(int intParameter)
                {
                    return intParameter + occurrences;
                }
            });
            this.size += occurrences;
        }
    }

    public boolean removeOccurrences(int item, final int occurrences)
    {
        if (occurrences < 0)
        {
            throw new IllegalArgumentException("Cannot remove a negative number of occurrences");
        }

        if (occurrences == 0)
        {
            return false;
        }

        int newValue = this.items.updateValue(item, 0, new IntToIntFunction()
        {
            public int valueOf(int intParameter)
            {
                return intParameter - occurrences;
            }
        });

        if (newValue <= 0)
        {
            this.size -= occurrences - newValue;
            this.items.removeKey(item);
            return newValue + occurrences != 0;
        }

        this.size -= occurrences;
        return true;
    }

    public void forEach(final IntProcedure procedure)
    {
        this.items.forEachKeyValue(new IntIntProcedure()
        {
            public void value(int key, int occurrences)
            {
                for (int i = 0; i < occurrences; i++)
                {
                    procedure.value(key);
                }
            }
        });
    }

    public IntHashBag select(final IntPredicate predicate)
    {
        final IntHashBag result = new IntHashBag();
        this.forEachWithOccurrences(new IntIntProcedure()
        {
            public void value(int each, int occurrences)
            {
                if (predicate.accept(each))
                {
                    result.addOccurrences(each, occurrences);
                }
            }
        });
        return result;
    }

    public IntHashBag reject(final IntPredicate predicate)
    {
        final IntHashBag result = new IntHashBag();
        this.forEachWithOccurrences(new IntIntProcedure()
        {
            public void value(int each, int occurrences)
            {
                if (!predicate.accept(each))
                {
                    result.addOccurrences(each, occurrences);
                }
            }
        });
        return result;
    }

    public <T> T injectInto(T injectedValue, ObjectIntToObjectFunction<? super T, ? extends T> function)
    {
        T result = injectedValue;
        IntIterator it = this.intIterator();
        while (it.hasNext())
        {
            result = function.valueOf(result, it.next());
        }
        return result;
    }

    @Override
    public boolean equals(Object otherBag)
    {
        if (otherBag == this)
        {
            return true;
        }
        if (!(otherBag instanceof IntBag))
        {
            return false;
        }
        final IntBag bag = (IntBag) otherBag;
        if (this.sizeDistinct() != bag.sizeDistinct())
        {
            return false;
        }

        return this.items.keysView().allSatisfy(new IntPredicate()
        {
            public boolean accept(int key)
            {
                return IntHashBag.this.occurrencesOf(key) == bag.occurrencesOf(key);
            }
        });
    }

    @Override
    public int hashCode()
    {
        final Counter result = new Counter();
        this.forEachWithOccurrences(new IntIntProcedure()
        {
            public void value(int eachItem, int occurrences)
            {
                result.add(eachItem ^ occurrences);
            }
        });
        return result.getCount();
    }

    @Override
    public String toString()
    {
        return this.makeString("[", ", ", "]");
    }

    public String makeString()
    {
        return this.makeString(", ");
    }

    public String makeString(String separator)
    {
        return this.makeString("", separator, "");
    }

    public String makeString(String start, String separator, String end)
    {
        Appendable stringBuilder = new StringBuilder();
        this.appendString(stringBuilder, start, separator, end);
        return stringBuilder.toString();
    }

    public void appendString(Appendable appendable)
    {
        this.appendString(appendable, ", ");
    }

    public void appendString(Appendable appendable, String separator)
    {
        this.appendString(appendable, "", separator, "");
    }

    public void appendString(
            final Appendable appendable,
            String start,
            final String separator,
            String end)
    {
        final boolean[] firstItem = {true};
        try
        {
            appendable.append(start);
            this.items.forEachKeyValue(new IntIntProcedure()
            {
                public void value(int each, int occurrences)
                {
                    try
                    {
                        for (int i = 0; i < occurrences; i++)
                        {
                            if (!firstItem[0])
                            {
                                appendable.append(separator);
                            }
                            appendable.append(String.valueOf(each));
                            firstItem[0] = false;
                        }
                    }
                    catch (IOException e)
                    {
                        throw new RuntimeException(e);
                    }
                }
            });
            appendable.append(end);
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }

    public int count(final IntPredicate predicate)
    {
        final Counter result = new Counter();
        this.forEachWithOccurrences(new IntIntProcedure()
        {
            public void value(int each, int occurrences)
            {
                if (predicate.accept(each))
                {
                    result.add(occurrences);
                }
            }
        });
        return result.getCount();
    }

    public boolean anySatisfy(IntPredicate predicate)
    {
        return this.items.keysView().anySatisfy(predicate);
    }

    public boolean allSatisfy(IntPredicate predicate)
    {
        return this.items.keysView().allSatisfy(predicate);
    }

    public boolean noneSatisfy(IntPredicate predicate)
    {
        return this.items.keysView().noneSatisfy(predicate);
    }

    public int detectIfNone(IntPredicate predicate, int ifNone)
    {
        return this.items.keysView().detectIfNone(predicate, ifNone);
    }

    public <V> MutableBag<V> collect(final IntToObjectFunction<? extends V> function)
    {
        final HashBag<V> result = HashBag.newBag(this.items.size());
        this.forEachWithOccurrences(new IntIntProcedure()
        {
            public void value(int each, int occurrences)
            {
                result.addOccurrences(function.valueOf(each), occurrences);
            }
        });
        return result;
    }

    public int max()
    {
        if (this.isEmpty())
        {
            throw new NoSuchElementException();
        }
        return this.items.keysView().max();
    }

    public int min()
    {
        if (this.isEmpty())
        {
            throw new NoSuchElementException();
        }
        return this.items.keysView().min();
    }

    public long sum()
    {
        final long[] result = {0L};
        this.forEachWithOccurrences(new IntIntProcedure()
        {
            public void value(int each, int occurrences)
            {
                result[0] += (long) each * occurrences;
            }
        });
        return result[0];
    }

    public int minIfEmpty(int defaultValue)
    {
        if (this.isEmpty())
        {
            return defaultValue;
        }
        return this.min();
    }

    public int maxIfEmpty(int defaultValue)
    {
        if (this.isEmpty())
        {
            return defaultValue;
        }
        return this.max();
    }

    public double average()
    {
        if (this.isEmpty())
        {
            throw new ArithmeticException();
        }
        return (double) this.sum() / (double) this.size();
    }

    public double median()
    {
        if (this.isEmpty())
        {
            throw new ArithmeticException();
        }
        int[] sortedArray = this.toSortedArray();
        int middleIndex = sortedArray.length >> 1;
        if (sortedArray.length > 1 && (sortedArray.length & 1) == 0)
        {
            int first = sortedArray[middleIndex];
            int second = sortedArray[middleIndex - 1];
            return ((double) first + (double) second) / 2.0;
        }
        return (double) sortedArray[middleIndex];
    }

    public int[] toArray()
    {
        final int[] array = new int[this.size()];
        final int[] index = {0};

        this.forEachWithOccurrences(new IntIntProcedure()
        {
            public void value(int each, int occurrences)
            {
                for (int i = 0; i < occurrences; i++)
                {
                    array[index[0]] = each;
                    index[0]++;
                }
            }
        });
        return array;
    }

    public int[] toSortedArray()
    {
        int[] array = this.toArray();
        Arrays.sort(array);
        return array;
    }

    public MutableIntList toList()
    {
        return IntArrayList.newList(this);
    }

    public MutableIntList toSortedList()
    {
        return IntArrayList.newList(this).sortThis();
    }

    public MutableIntSet toSet()
    {
        return IntHashSet.newSet(this.items.keysView());
    }

    public MutableIntBag toBag()
    {
        return IntHashBag.newBag(this);
    }

    public LazyIntIterable asLazy()
    {
        return new LazyIntIterableAdapter(this);
    }

    public MutableIntBag asUnmodifiable()
    {
        return new UnmodifiableIntBag(this);
    }

    public MutableIntBag asSynchronized()
    {
        return new SynchronizedIntBag(this);
    }

    public ImmutableIntBag toImmutable()
    {
        return IntBags.immutable.withAll(this);
    }

    public IntIterator intIterator()
    {
        return new InternalIterator();
    }

    public void writeExternal(final ObjectOutput out) throws IOException
    {
        out.writeInt(this.items.size());
        try
        {
            this.items.forEachKeyValue(new IntIntProcedure()
            {
                public void value(int each, int occurrences)
                {
                    try
                    {
                        out.writeInt(each);
                        out.writeInt(occurrences);
                    }
                    catch (IOException e)
                    {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
        catch (RuntimeException e)
        {
            if (e.getCause() instanceof IOException)
            {
                throw (IOException) e.getCause();
            }
            throw e;
        }
    }

    public void readExternal(ObjectInput in) throws IOException
    {
        int size = in.readInt();
        this.items = new IntIntHashMap(size);
        for (int i = 0; i < size; i++)
        {
            this.addOccurrences(in.readInt(), in.readInt());
        }
    }

    private class InternalIterator implements IntIterator
    {
        private final IntIterator intIterator = IntHashBag.this.items.keysView().intIterator();

        private int currentItem;
        private int occurrences;

        public boolean hasNext()
        {
            return this.occurrences > 0 || this.intIterator.hasNext();
        }

        public int next()
        {
            if (this.occurrences == 0)
            {
                this.currentItem = this.intIterator.next();
                this.occurrences = IntHashBag.this.occurrencesOf(this.currentItem);
            }
            this.occurrences--;
            return this.currentItem;
        }
    }
}
TOP

Related Classes of com.gs.collections.impl.bag.mutable.primitive.IntHashBag

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.