Hello All,

I want to sort my list order by sno.

This is my code,

List<Employee>list=new ArrayList<Employee>();

Employee class has fields, one of field is sno (its String type); this field values are like this format

1.2.1
1.2.3
1.5.5
1.5.3

I want to sort this serial no. I used comparator but I dint get sorted output. Is there any option to sort this format of values?

Thanks,

Re: How to sort string values in java 80 80

and what was your implementation of the compare method?

Re: How to sort string values in java 80 80

A Comparator is the right way to do it, so there seems to be something wrong with your implementation. If you post your code someone will help.

Re: How to sort string values in java 80 80

ArrayList isn't sorted. You need to not just use a Comparator but also a sorted Collection, like TreeSet.

Re: How to sort string values in java 80 80

Hi jwenting,

Collection can be sorted. So using

Collections.sort(collectionName, new Comparator<collectionName>(){ ... };);

will work, just has others have said.

Re: How to sort string values in java 80 80

yes, you can use Collections.sort, but that doesn't get you a List that will retain sort order if you add items to it.

Re: How to sort string values in java 80 80

...but that doesn't get you a List that will retain sort order if you add items to it.

The OP didn't say anything about adding items after sorting have been done. Did s/he?

More so, the sorting routine could be made a method and then it's called whenever..

Re: How to sort string values in java 80 80

OP claimed to have used a Comparator and not get a sorted output. Most likely they applied the Comparator BEFORE adding the data to the Collection. Using a SortedSet implementation allows that.

Re: How to sort string values in java 80 80

OP claimed to have used a Comparator and not get a sorted output

And that is why am with [ JamesCherrill ] on this with the post A Comparator is the right way to do it, so there seems to be something wrong with your implementation. If you post your code someone will help.
That is about a week ago now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.