Does Java have a multiset data structure like the one in C++ STL?

后端 未结 7 558
灰色年华
灰色年华 2020-12-28 13:00

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

相关标签:
7条回答
  • 2020-12-28 13:36

    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.

    0 讨论(0)
  • 2020-12-28 13:41

    There is no Multiset in the standard Java libraries. You should use the Google Guava framework which contains Multiset classes. See

    0 讨论(0)
  • 2020-12-28 13:42

    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.

    0 讨论(0)
  • 2020-12-28 13:49

    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.

    0 讨论(0)
  • 2020-12-28 13:50
    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!

    0 讨论(0)
  • 2020-12-28 13:55

    You could use a PriorityQueue The elements are sorted in their natural order, or if you provide one, by comparator, and duplicates are allowed.

    0 讨论(0)
提交回复
热议问题