I want to develop one sorting demo for car list. i am using data table to display car list. Now actually i want to sort the list by car color. here it is not sort by alphabetic order. I want to use my custom order like Red car come first, then Blue, etc.
For that i try to use Java Comparator and comparable but its allow to sort in alphabetic order only.
So, can any one guide me the way to implement and technique to use that wise the sorting became faster.
If you're writing your own Comparator class, you can implement any sorting you want. You're just going to have to define the sort order - what the Comparator has to do is decide which object comes first whenever it's given two to compare.
If you post the Comparator you've tried so far, we might be able to help you with it.
akhtar qureshi wrote:can you please help me in sort by my custom sorting order.
Not until you define what your custom sort order is. If you don't want to sort them alphabetically, then how do you want to sort them - by RGB value, by wavelength, by number of letters in their name, etc, etc. There are many possibilites - which do you want to use ?
You say in your original post
akhtar qureshi wrote:I want to use my custom order like Red car come first, then Blue, etc.
You need to define this further. Does yellow come before or after Blue, what about green ? Do you want to sort different shades of a particular colour or are they all considered the same ?
OK. You're currently storing your colours as a String, and you're using String.compareTo() to sort them. Which, as you noticed, produces an alphabetical ordering, which isn't what you want.
So, next question. What order do you want your colours to come in? And what colours are possible? Before you can write an algorithm to sort them, you need to define what the ordering should be. All you've said so far is that "Red" should come before "Blue".
I think thinks might be easier if you stopped using Strings for the colours. If there are a fixed number of colours you can use, I'd suggest using an enum. If you define your enum in the order you want the colours to appear, then sorting them will be simple (enums are Comparable). If you want to be able to use any colour, you need to decide how they might be sorted.
You need to change the color field of your CarSort class to be of type sortOrder. Then your compare method just becomes
Of course, you will also need to change your constructor, setColor and getColor methods to handle the type change.