Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Sorted List/Set that allows duplicates

Tags:

java

sorting

I've got a program that has a bunch of data objects. Each of these implement Comparable, and are set up to sort from highest to lowest (based on a simple long value) including duplicates values. I want these objects to be stored in a set/list such that I can iterate over it, and pull out each object in its respective place.

I've looked at using a TreeSet, however this does not allow duplicates, and so only keeps one of the many objects with the same values. I then found TreeMultiset, which could keep elements with the same value. The only problem with that is that it simply stores duplicates of the same object, rather than multiple objects that are equal.

Is there a library/built in object that I can use that will do what I want, or should I create an implementation myself?

Note: the reason I don't want the object duplicating in TreeMultiset is because the object contains a unique ID to a user, and a time value (this is what is compared)

like image 414
ZephireNZ Avatar asked Feb 02 '26 13:02

ZephireNZ


1 Answers

You can box to your same objects with a wrapper class such as:

class MyContainer:IComparable{
    public int compareValue;
    public List<object> data;

    public int CompareTo(MyContainer other){
        return this.compareValue - other.compareValue;
    }

    public void AddItem(object item){
        data.add(item);
    }

    public object GetItem(int Id){...}
}

class Program()
{
 TreeSet<MyContainer> data;
 public static void main(){
    data.AddToContainer("aaa");
    data.AddToContainer("aaa");
    data.AddToContainer("ccc");

 }

 public void AddToContainer(object item){
    if(data.contains(item)){
       data.get(item).AddItem(item);  
    }
    else{
       MyContainer cont = new MyContainer();
       cont.AddItem(item);
       data.add(cont);
    }
  }

}
like image 61
eakgul Avatar answered Feb 05 '26 03:02

eakgul