I need a data structure which works like the STL multiset but the TreeSet in Java doesn\'t allow duplicate elements. Is there any built-in data structure in Java which is eq
Algorithms 4th edition has a Bag implementation that's available on the book's web site. You can view the javadoc online as well.
The Bag class represents a bag (or multiset) of generic items. It supports insertion and iterating over the items in arbitrary order.
You'll probably just want to have a look at the source code if Bag
is all you need, but there are a lot of other interesting things in algs4.jar
, so it's worth a look.
There is no Multiset in the standard Java libraries. You should use the Google Guava framework which contains Multiset classes. See
Since 1.8, Map allows you to do this:
map.computeIfAbsent(key, k -> new HashSet<V>()).add(v);
Each value is added into a Set, which is created on demand.
You may need to change remove() too.
Apache Commons Collections has Bag and SortedBag interfaces. It sounds like TreeBag might meet your needs, but there are plenty of implementations to choose from.
TreeSet<Integer> set = new TreeSet<>();
TreeSet<Integer> multiset = new TreeSet<>((i, j) -> i < j ? 1 : -1);
Make a set multiset just by making 1 != 1!
You could use a PriorityQueue The elements are sorted in their natural order, or if you provide one, by comparator, and duplicates are allowed.