Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a set in Java

Framework used: Spring

ORM used: Hibernate

I have two classes

class BatchExceptionDetails{
...
private Set<BatchExceptionComments> batchExceptionComments;
}

class BatchExceptionComments implements Comparable<BatchExceptionComments>{
...
@Override
    public int compareTo(BatchExceptionComments o) {
        // TODO Auto-generated method stub

        return this.getAddedOn().compareTo(o.getAddedOn());
    }
}

They are mapped with one to many mapping.

There is a set of BatchExceptionComments in BatchExceptionDetails.

I want to sort the set on the basis of Date. BatchExcpetionComment has an attribute of type java.util.Date i.e. addedOn. I want the latest comment to be the first element of set.

The set I am receiving is not sorted. Will you please guide me where I am going wrong.

Thanks in advance

like image 889
Ayush Avatar asked Jan 28 '23 03:01

Ayush


2 Answers

Set is an interface, so it is not possible to establish if it is sortable or not. You have to use the correct implementation, like TreeSet. If you want to emphasize that it is a sorted set, you should use the SortedSet interface. TreeSet implements SortedSet.

Alternatively you can use a List and then you can sort it using Collections.sort.

like image 189
Lorelorelore Avatar answered Jan 29 '23 16:01

Lorelorelore


After some goofing around I found a solution.

I just declared the set

private Set<BatchExceptionComments> batchExceptionComments;

Instead of using Comparable I used Order By to arrange the set.

 <set name="batchExceptionComments" table="BATCH_EXCEPTION_COMMENTS" 
                inverse="true" fetch="select" lazy="false" order-by="commentId">
            <key>
                <column name="EXCEPTION_ID" not-null="true" />
            </key>
            <one-to-many class="com.beans.BatchExceptionComments" />
        </set>

I believe ordering by Id will be better.

P.S. I am using hbm.xml instead of annotation

like image 22
Ayush Avatar answered Jan 29 '23 15:01

Ayush