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

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

/*
* 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.CharIterable;
import com.gs.collections.api.LazyCharIterable;
import com.gs.collections.api.bag.MutableBag;
import com.gs.collections.api.bag.primitive.CharBag;
import com.gs.collections.api.bag.primitive.ImmutableCharBag;
import com.gs.collections.api.bag.primitive.MutableCharBag;
import com.gs.collections.api.block.function.primitive.CharToObjectFunction;
import com.gs.collections.api.block.function.primitive.ObjectCharToObjectFunction;
import com.gs.collections.api.block.function.primitive.IntToIntFunction;
import com.gs.collections.api.block.predicate.primitive.CharPredicate;
import com.gs.collections.api.block.procedure.primitive.CharProcedure;
import com.gs.collections.api.block.procedure.primitive.CharIntProcedure;
import com.gs.collections.api.iterator.CharIterator;
import com.gs.collections.api.list.primitive.MutableCharList;
import com.gs.collections.api.set.primitive.CharSet;
import com.gs.collections.api.set.primitive.MutableCharSet;
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.CharBags;
import com.gs.collections.impl.lazy.primitive.LazyCharIterableAdapter;
import com.gs.collections.impl.list.mutable.primitive.CharArrayList;
import com.gs.collections.impl.map.mutable.primitive.CharIntHashMap;
import com.gs.collections.impl.set.mutable.primitive.CharHashSet;
import net.jcip.annotations.NotThreadSafe;

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

    private CharIntHashMap items;
    private int size;

    public CharHashBag()
    {
        this.items = new CharIntHashMap();
    }

    public CharHashBag(int size)
    {
        this.items = new CharIntHashMap(size);
    }

    public CharHashBag(CharIterable iterable)
    {
        this();
        this.addAll(iterable);
    }

    public CharHashBag(CharHashBag bag)
    {
        this.items = new CharIntHashMap(bag.sizeDistinct());
        bag.forEachWithOccurrences(new CharIntProcedure()
        {
            public void value(char item, int occurrences)
            {
                CharHashBag.this.addOccurrences(item, occurrences);
            }
        });
    }

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

    public static CharHashBag newBagWith(char... source)
    {
        CharHashBag result = new CharHashBag();
        result.addAll(source);
        return result;
    }

    public static CharHashBag newBag(CharIterable source)
    {
        if (source instanceof CharHashBag)
        {
            return new CharHashBag((CharHashBag) source);
        }

        return new CharHashBag(source);
    }

    public static CharHashBag newBag(CharBag source)
    {
        final CharHashBag result = new CharHashBag();
        source.forEachWithOccurrences(new CharIntProcedure()
        {
            public void value(char 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 CharHashBag with(char element)
    {
        this.add(element);
        return this;
    }

    public CharHashBag with(char element1, char element2)
    {
        this.add(element1);
        this.add(element2);
        return this;
    }

    public CharHashBag with(char element1, char element2, char element3)
    {
        this.add(element1);
        this.add(element2);
        this.add(element3);
        return this;
    }

    public CharHashBag withAll(CharIterable iterable)
    {
        this.addAll(iterable);
        return this;
    }

    public CharHashBag without(char element)
    {
        this.remove(element);
        return this;
    }

    public CharHashBag withoutAll(CharIterable iterable)
    {
        this.removeAll(iterable);
        return this;
    }

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

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

    public boolean containsAll(CharIterable source)
    {
        return source.allSatisfy(new CharPredicate()
        {
            public boolean accept(char each)
            {
                return CharHashBag.this.contains(each);
            }
        });
    }

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

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

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

    public boolean remove(char 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(char... source)
    {
        if (source.length == 0)
        {
            return false;
        }

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

    public boolean addAll(CharIterable source)
    {
        if (source.isEmpty())
        {
            return false;
        }
        if (source instanceof CharBag)
        {
            CharBag otherBag = (CharBag) source;
            otherBag.forEachWithOccurrences(new CharIntProcedure()
            {
                public void value(char each, int occurrences)
                {
                    CharHashBag.this.addOccurrences(each, occurrences);
                }
            });
        }
        else
        {
            CharIterator iterator = source.charIterator();
            while (iterator.hasNext())
            {
                char each = iterator.next();
                this.add(each);
            }
        }
        return true;
    }

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

    public boolean removeAll(CharIterable source)
    {
        if (source.isEmpty())
        {
            return false;
        }
        int oldSize = this.size();
        if (source instanceof CharBag)
        {
            CharBag otherBag = (CharBag) source;
            otherBag.forEachWithOccurrences(new CharIntProcedure()
            {
                public void value(char each, int occurrences)
                {
                    int oldOccurrences = CharHashBag.this.items.removeKeyIfAbsent(each, 0);
                    CharHashBag.this.size -= oldOccurrences;
                }
            });
        }
        else
        {
            CharIterator iterator = source.charIterator();
            while (iterator.hasNext())
            {
                char each = iterator.next();
                int occurrences = this.items.removeKeyIfAbsent(each, 0);
                this.size -= occurrences;
            }
        }
        return this.size() != oldSize;
    }

    public boolean retainAll(CharIterable source)
    {
        int oldSize = this.size();
        final CharSet sourceSet = source instanceof CharSet ? (CharSet) source : source.toSet();
        CharHashBag retained = this.select(new CharPredicate()
        {
            public boolean accept(char key)
            {
                return sourceSet.contains(key);
            }
        });
        if (retained.size() != oldSize)
        {
            this.items = retained.items;
            this.size = retained.size;
            return true;
        }
        return false;
    }

    public boolean retainAll(char... source)
    {
        return this.retainAll(CharHashSet.newSetWith(source));
    }

    public void addOccurrences(char 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(char 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 CharProcedure procedure)
    {
        this.items.forEachKeyValue(new CharIntProcedure()
        {
            public void value(char key, int occurrences)
            {
                for (int i = 0; i < occurrences; i++)
                {
                    procedure.value(key);
                }
            }
        });
    }

    public CharHashBag select(final CharPredicate predicate)
    {
        final CharHashBag result = new CharHashBag();
        this.forEachWithOccurrences(new CharIntProcedure()
        {
            public void value(char each, int occurrences)
            {
                if (predicate.accept(each))
                {
                    result.addOccurrences(each, occurrences);
                }
            }
        });
        return result;
    }

    public CharHashBag reject(final CharPredicate predicate)
    {
        final CharHashBag result = new CharHashBag();
        this.forEachWithOccurrences(new CharIntProcedure()
        {
            public void value(char each, int occurrences)
            {
                if (!predicate.accept(each))
                {
                    result.addOccurrences(each, occurrences);
                }
            }
        });
        return result;
    }

    public <T> T injectInto(T injectedValue, ObjectCharToObjectFunction<? super T, ? extends T> function)
    {
        T result = injectedValue;
        CharIterator it = this.charIterator();
        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 CharBag))
        {
            return false;
        }
        final CharBag bag = (CharBag) otherBag;
        if (this.sizeDistinct() != bag.sizeDistinct())
        {
            return false;
        }

        return this.items.keysView().allSatisfy(new CharPredicate()
        {
            public boolean accept(char key)
            {
                return CharHashBag.this.occurrencesOf(key) == bag.occurrencesOf(key);
            }
        });
    }

    @Override
    public int hashCode()
    {
        final Counter result = new Counter();
        this.forEachWithOccurrences(new CharIntProcedure()
        {
            public void value(char eachItem, int occurrences)
            {
                result.add((int) 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 CharIntProcedure()
            {
                public void value(char 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 CharPredicate predicate)
    {
        final Counter result = new Counter();
        this.forEachWithOccurrences(new CharIntProcedure()
        {
            public void value(char each, int occurrences)
            {
                if (predicate.accept(each))
                {
                    result.add(occurrences);
                }
            }
        });
        return result.getCount();
    }

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

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

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

    public char detectIfNone(CharPredicate predicate, char ifNone)
    {
        return this.items.keysView().detectIfNone(predicate, ifNone);
    }

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

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

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

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

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

    public char maxIfEmpty(char 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();
        }
        char[] sortedArray = this.toSortedArray();
        int middleIndex = sortedArray.length >> 1;
        if (sortedArray.length > 1 && (sortedArray.length & 1) == 0)
        {
            char first = sortedArray[middleIndex];
            char second = sortedArray[middleIndex - 1];
            return ((double) first + (double) second) / 2.0;
        }
        return (double) sortedArray[middleIndex];
    }

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

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

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

    public MutableCharList toList()
    {
        return CharArrayList.newList(this);
    }

    public MutableCharList toSortedList()
    {
        return CharArrayList.newList(this).sortThis();
    }

    public MutableCharSet toSet()
    {
        return CharHashSet.newSet(this.items.keysView());
    }

    public MutableCharBag toBag()
    {
        return CharHashBag.newBag(this);
    }

    public LazyCharIterable asLazy()
    {
        return new LazyCharIterableAdapter(this);
    }

    public MutableCharBag asUnmodifiable()
    {
        return new UnmodifiableCharBag(this);
    }

    public MutableCharBag asSynchronized()
    {
        return new SynchronizedCharBag(this);
    }

    public ImmutableCharBag toImmutable()
    {
        return CharBags.immutable.withAll(this);
    }

    public CharIterator charIterator()
    {
        return new InternalIterator();
    }

    public void writeExternal(final ObjectOutput out) throws IOException
    {
        out.writeInt(this.items.size());
        try
        {
            this.items.forEachKeyValue(new CharIntProcedure()
            {
                public void value(char each, int occurrences)
                {
                    try
                    {
                        out.writeChar(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 CharIntHashMap(size);
        for (int i = 0; i < size; i++)
        {
            this.addOccurrences(in.readChar(), in.readInt());
        }
    }

    private class InternalIterator implements CharIterator
    {
        private final CharIterator charIterator = CharHashBag.this.items.keysView().charIterator();

        private char currentItem;
        private int occurrences;

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

        public char next()
        {
            if (this.occurrences == 0)
            {
                this.currentItem = this.charIterator.next();
                this.occurrences = CharHashBag.this.occurrencesOf(this.currentItem);
            }
            this.occurrences--;
            return this.currentItem;
        }
    }
}
TOP

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

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.