Java sort based on two columns - Without comparator - java

Here is the question:
Java sort based on two columns
But, can anyone explain how to do without using Comparator? In other words, How the comparator works internally for sorting multiple columns?

The sort method must have some way of finding out the relative order of pairs of rows. There are two supported ways of doing it using the normal sorts. Either use instances of a class that implements Comparable to represent rows, or use a Comparator.
If you don't want to do either of those, you would have to write your own, specialized, sort method. When it needs to compare two rows, it would look first at the higher priority column. If the rows differ in that column, that gives there order. If they are equal in that column, order them based on the second column.
That said, using a standard sort with either Comparable rows or a Comparator is much better than mixing up the sort logic and the comparison logic. Comparator is the more flexible way.

Related

Sort arraylist in X different ways at the same time

If I have an ArrayList of custom objects which I need to be able to display them in various sortings (e.g. 4 types of sort so 4 comparators to use the proper member variables of the objects for the sorting) what is the most efficient way to do it?
I don’t think having e.g. 4 array lists of the objects sorted according to a specific comparator is optimal.
Is there another more efficient way than this?
Please note that I would need to have these objects sorted at the same time as they will be presented in the same page. So I can’t sort on demand
You could have different index arrays containing integers that are interpeted as indices of your original ArrayList. These can be sorted in different ways.
To access the list elements, use something like this:
list.get(index1.get(i));
I guess that FlyWeight design pattern could match your expectations.
Flyweight pattern is primarily used to reduce the number of objects created and to decrease memory footprint and increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to decrease object count thus improving the object structure of application.
As you have your objects in an ArrayList, you can build up as many ArrayLists as different kinds of sorts you need for storing flyweight objects (basically id, order).

Why can't we use only comparable in every situation?

Possible Duplicate of
When should a class be Comparable and/or Comparator?
I understand the difference that is given in this link.
And also in the book that i am referring it is given that we can not use comparable when we need to sort the objects on the basis of more than one fields.
My Question:
I just want an example where we could not possibly use comparable and have to go for comparator in order to compare and please also show that with comparable why can't we compare on two different fields of object.
If you find this question as duplicate please provide link,, i have searched many questions but none has the example that i wanted.
If a class implements Comparable, this defines what is usually considered the natural ordering of it elements. In some cases this is the only ordering that may make sense, in other cases it might be the most widely used ordering. If you look for example at numbers, there is probably only one (total) ordering that makes sense (except maybe for taking the reverse). As others already have pointed out, their are other objects that have other useful orderings. What makes the primary ordering (or if there is even one) depends on your application. If you manage persons with adresses in you application, phonebook sort order could be considered the natural order if this is the most widely used one and sorting by age could be a secondary. Slightly OT: Beware of cases where non equal objects are considered equal wrt to the ordering, this may yield problems with containers like OrderedList etc.
Comparing apples with each other will result in classes of equal apples, like red ones, green ones, old and fresh ones. That's OK as long as you only interested in a rather broad equality. But if you you are going to receive a paycheck you are very happy that you are identifiable within you equality class.
So compareto is good for sorting and clustering and equals/hashcode is got for identification.
Comparable is mostly used when there is a 'known' default sort order and the object or class that we are ordering is editable or owned by the developer making the change.
Comparator is suitable where the class or object being ordered is not owned by the developer making the change like a web service response. It is also preferred when the natural ordering doesn't fit the objective that needs to be accomplished.

Is there a good Java library for generation of order preserving O(1) hash codes, based on a set of attributes and a comparator?

Given set of attributes and a comparator I'd like to generate an order preserving hash code that provides O(1) access. Is there a Java library for this sort of thing or would I have to design the hash function myself?
Try:
java.util.LinkedHashMap()
There is no single collection that will do this. Depending on the detail requirements there are several options to chose from.
For simplicity, I would just use a HashMap for lookups and when I need the sorted data, I'd make a copy of the values and sort it:
List<?> sorted = new ArrayList<?>(hashMap.values());
Collections.sort(sorted, Comparator<?>);
This suffices for most real world use cases.
You could also write your own super-container that internally holds the elements in two collections, one HashMap and maybe a TreeSet. You can then easily provide access methods that make use of the collection better for the purpose of the method. Just make sure you make additions and removals affect both the contained collections.

Insertion sort with strings

I'm curious how an insertion sort would be for strings. I know how to do with numbers.
Could someone show me an implementation?
No, it's not for homework.
Thanks.
The sorting algorithm is pretty much the same no matter what you're sorting. The only difference is that with Strings (or any type of Object) you need to use the compareTo method rather than simply if (a < b).
You should be able to adapt an insertion sort for numbers to Strings by using String.compareTo to determine whether Strings are 'less than' or 'greater than' each other.
Additionally, a quick google search turns up several implementations, like this one which uses the general Comparable interface (which String implements).

The Efficient way to sort a collection of Objects

I have a requirement to sort a collection of objects, They are shown on a web page in tabular format. My sorted collection is created like
TreeSet<MyObject> objs= new TreeSet<MyObject>();
Currently MyObject is implementing Comparable interface to provide sorting. In the compareTo method object is checked against the date of creation as my sorting logic.
Now I have got a requirement to sort this collection on the basis of various other instance variable of the class. After exploring options to achieve this I have got two ideas for this execution,
Use a Comparator. In this class I can implement my logic to sort the collection.
Create a database query to return the sorted collection for MyObject. I can use ORDER BY Optimization to achieve this.
So, I would like to know your opinion on the both approaches and what should be best optimum solution for such a requirement.
If you already have the objects in memory, then sorting them with a Comparator is definitely faster.
If you query them from the DB each time anyway, then using ORDER BY is definitely easier and probably faster as well.

Categories