From c98e7a86ee1e788dd935e927a6903772e7795dd6 Mon Sep 17 00:00:00 2001 From: "Ray J. Greenwell" Date: Thu, 29 Jan 2015 15:55:13 -0800 Subject: [PATCH] MultisetUtil. Originally lived in projectx and had a bunch more interesting stuff. But the code that used it (gates, minerals, themes) went away because all that mineral stuff went away. Kept what's still in use. In particular, singleton() is quite useful (really, Google should add it to Multisets or ImmutableMultiset). The count ordering stuff is perhaps semi-deprecated, since Google has added Multisets.copyHighestCountFirst(). --- .../com/threerings/util/MultisetUtil.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/main/java/com/threerings/util/MultisetUtil.java diff --git a/src/main/java/com/threerings/util/MultisetUtil.java b/src/main/java/com/threerings/util/MultisetUtil.java new file mode 100644 index 0000000..919cbaa --- /dev/null +++ b/src/main/java/com/threerings/util/MultisetUtil.java @@ -0,0 +1,49 @@ +// +// ooo-util - a place for OOO utilities +// Copyright (C) 2011 Three Rings Design, Inc., All Rights Reserved +// http://github.com/threerings/ooo-util/blob/master/LICENSE + +package com.threerings.util; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableMultiset; +import com.google.common.collect.Multiset; +import com.google.common.collect.Ordering; +import com.google.common.primitives.Ints; + +/** + * Convenience functions for working with Multisets. + */ +public class MultisetUtil +{ + /** An Ordering that compares Multiset.Entrys by count. */ + public static final Ordering> ENTRY_COUNT_ORDERING = + new Ordering>() { + public int compare (Multiset.Entry left, Multiset.Entry right) { + return Ints.compare(left.getCount(), right.getCount()); + } + }; + + /** + * Return a Function that will transform objects to their corresponding count in the + * specified Multiset. + */ + public static Function countFunction (final Multiset set) + { + return new Function() { + public Integer apply (Object o) { + return set.count(o); + } + }; + } + + /** + * Create an ImmutableMultiset with a single element with the specified count. + */ + public static ImmutableMultiset singleton (T element, int count) + { + return ImmutableMultiset.builder() + .addCopies(element, count) + .build(); + } +}