其他分享
首页 > 其他分享> > Guava - Set集合

Guava - Set集合

作者:互联网

当我们在统计一个字符串中每个单词出现的次数时,通常的做法是分割字符串,遍历字符串,然后放到一个map里面,来进行统计,Guava中提供了类似功能的集合,Multiset

        String strWorld="wer dffd ddsa dfd dreg de dr ce ghrt cf gt ser tg ghrt cf gt " +
                "ser tg gt kldf dfg vcd fg gt ls lser dfr wer dffd ddsa dfd dreg de dr " +
                "ce ghrt cf gt ser tg gt kldf dfg vcd fg gt ls lser dfr";
        List<String> stringList = Splitter.on(" ")
                .trimResults()
                .splitToList(strWorld);//把字符串转换为集合
        HashMultiset<String> multisets = HashMultiset.create();//创建一个Multiset集合
        multisets.addAll(stringList);
        Iterator<String> iterator = multisets.iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            System.out.println(next+" count: "+multisets.count(next));
        }

代码如此简洁清晰。

实现逻辑

内部使用Map进行实现,
HashMultiset.create()

public final class HashMultiset<E> extends AbstractMapBasedMultiset<E>
   public static <E> HashMultiset<E> create() {
        return new HashMultiset();
    }
    private HashMultiset() {
        super(new HashMap());
    }
    ... ...
 }
abstract class AbstractMultiset<E> extends AbstractCollection<E> implements Multiset<E> {
    public boolean add(@Nullable E element) {
        this.add(element, 1);
        return true;
    }
}

AbstractMapBasedMultiset

abstract class AbstractMapBasedMultiset<E> extends AbstractMultiset<E> implements Serializable {
    private transient Map<E, Count> backingMap;
    private transient long size;
    @GwtIncompatible
    private static final long serialVersionUID = -2250766705698539974L;

    protected AbstractMapBasedMultiset(Map<E, Count> backingMap) {
        this.backingMap = (Map)Preconditions.checkNotNull(backingMap);
        this.size = (long)super.size();
    }
    public int add(@Nullable E element, int occurrences) {
        if(occurrences == 0) {
            return this.count(element);
        } else {
            Preconditions.checkArgument(occurrences > 0, "occurrences cannot be negative: %s", occurrences);
            Count frequency = (Count)this.backingMap.get(element);
            int oldCount;
            if(frequency == null) {
                oldCount = 0;
                this.backingMap.put(element, new Count(occurrences));
            } else {
                oldCount = frequency.get();
                long newCount = (long)oldCount + (long)occurrences;
                Preconditions.checkArgument(newCount <= 2147483647L, "too many occurrences: %s", newCount);
                frequency.add(occurrences);
            }

            this.size += (long)occurrences;
            return oldCount;
        }
    }
    ... ...
}

标签:Set,long,element,gt,occurrences,集合,backingMap,Guava,HashMultiset
来源: https://www.cnblogs.com/hitechr/p/10473711.html