pribic's blog

By pribic, history, 5 weeks ago, In English

Since we don't have multisets in Java, tried my luck to build one.

Reviews and feedbacks are welcome.

Basic idea is we keep another frequency map for each object. Whenever, we add an element, we update this frequency map as well. Whenever we remove, we check if that element now has frequency 0, if yes then only we remove it from set. Also we are using TreeSet so all the elements will be sorted and all TreeSet features are available out of the box.

I solved using this.

Submission —

static class MultiSet<T> extends TreeSet<T> {
    Map<T, Integer> frequency;

    public MultiSet() {
      this.frequency = new HashMap<>();

    public boolean add(T t) {
      frequency.put(t, frequency.getOrDefault(t, 0) + 1);
      return super.add(t);

    public boolean remove(Object o) {
      if (!frequency.containsKey(o))
        return false;
      frequency.put((T) o, frequency.getOrDefault(o, 1) - 1);
      if (frequency.get(o) == 0) {
      return true;

    public String toString() {
      return new StringJoiner(", ", MultiSet.class.getSimpleName() + "[", "]")
        .add("frequency=" + frequency)
  • Vote: I like it
  • +6
  • Vote: I do not like it

5 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by pribic (previous revision, new revision, compare).