The Efficient way to sort a collection of Objects - java

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.

Related

Collection Map in Java

I want to write my own Map in Java. I know how map works, but i don't really know where you can keep keys and values. Can i keep them for example in List? So the keys would be store in the list and values would be store in another list?
Best would be if you checked out some of the concepts behind HashMap, TreeMap, HeapMap etc.
Once you understand those concepts, you're far better prepared for writing your own map when it comes to speed.
In other words: unless you know the concepts of all available implementations, it is very unlikely your wheel-re-invention will be a better solution.
Also be sure to test your implementations very thoroughly, as Collection are the backbone and heart of any good application.
Two very very simple (but slow) solutions are these:
1) As suggested above, you can use an ArrayList<Pair> and add your custom getItemByKey() (in Java commonly named 'get') method.
2) You can use two arrays, both keeping the same size, and keeping keys and values matched by their respective indices.
For choosing the data structure there's not better than Array (not all time but almost) of Entries (key/value) because the main goal of map is to map objects for objects, so mapping keys to values.
Using arrays for fast and constant access O(1), but you have a little problem, when your map is full, you have to create new Array and copy old entries.
Note: HashMap works in the same way.

Is it bad practice to return an iterable in a method?

I have often read in many places that one should avoid returning an iterable and return a collection instead. For example -
public Iterable<Maze> Portals() {
// a list of some maze configurations
List<Maze> mazes = createMazes();
...
return Collections.unmodifiableList(mazes);
}
Since returning an iterable is only useful for using it in foreach loop, while collection already provides an iterator and provides much more control. Could you please tell me when it is beneficial to specifically return an iterable in a method? Or we should always return a collection instead?
Note : This question is not about Guava library
Returning an Iterable would be beneficial when we need to lazily load a collection that contains a lot of elements.
The following quote from Google Collections FAQ seems to support the idea of lazy loading:
Why so much emphasis on Iterators and Iterables?
In general, our methods do not require a Collection to be passed in
when an Iterable or Iterator would suffice. This distinction is
important to us, as sometimes at Google we work with very large
quantities of data, which may be too large to fit in memory, but which
can be traversed from beginning to end in the course of some
computation. Such data structures can be implemented as collections,
but most of their methods would have to either throw an exception,
return a wrong answer, or perform abysmally. For these situations,
Collection is a very poor fit; a square peg in a round hole.
An Iterator represents a one-way scrollable "stream" of elements, and
an Iterable is anything which can spawn independent iterators. A
Collection is much, much more than this, so we only require it when we
need to.
I can see advantages and disadvantages:
One advantage is that Iterable is a simpler interface than Collection. If you have a non-standard collection type, it may be easier to make it Iterable than Collection. Indeed, there are some kinds of collection for which some of the Collection methods are problematic to implement. For example, lazy collections types and collections where you don't want to rely on the standard equals(Object) method to determine membership.
One disadvantage is that Iterable is functionality poor. If you have a concrete type that implements Collection, and you return it as an Iterable, you are removing the possibility that the code can (directly) call a variety of useful collection methods.
There are some cases where neither Iterable or Collection are a good fit; e.g. specialist collections of primitive types ... where you need to avoid the overheads of using the primitive wrapper types.
You can't really say whether it is good or bad practice to return an Iterable. It depends on the circumstances; e.g. the purpose of the API you are designing, and the requirements or constraints that you want / need to place on it.
The problem is that if underlying collection changes, you will be in trouble.
If you are using a collection which throws concurrentmodification exception then you have to take care of it as well but with collection there are no such issues.
Return the most specific type that makes sense for the use in question. If you have a method that's creating a new collection, for example, or you can easily wrap the collection in an unmodifiable wrapper, returning the collection as a Collection, or even a List or Set, makes the client developer's life a little easier.
Returning Iterable makes sense for code where the values may be generated on-the-fly; you could imagine a Fibonacci generator, for example, that created an Iterator that calculated the next number instead of trying to store some lookup table. If you're writing framework or interface code where such a "streaming" sort of API might be useful (Guava and its functional classes do a good bit of this), then specifying Iterable instead of a collection type might be worth the loss of flexibility on the consumer side.

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.

How to store list of countries in Java

I need a Java structure which can store list of all countries. Which Java data structure will you recommend?
You may use Set collection implementations like HashSet which avoids duplicates (if just names). If you want to keep country code and name, then may be Map collection.
Are you going to iterate over the collection?
If so, java.util.ArrayList.
Are you going to use it to do some kind of look up? Like a 'does this exist' scenario?
If so, java.util.HashSet
Do you need to attach additional information to each country?
If so, java.util.HashMap
Do you need a lookup and an ordered iteration?
If so, java.util.TreeSet.
There's also concurrency to be concerned about, but I didn't see any mention of it, so I'll leave off those guys.
You should use a HashSet which provides both the uniqueness of elements in a set and the constant time of key search.
Try to use Dictionary<k,v> , I recommend it
I think a HashSet should be suitable so long as you don't expect to have duplicates. HashSets provide constant time lookup which will speed up searches. You can consider other Thread-safe variants like Collections.SynchronizedSet or CopyOnWriteArrayList if you expect the data structure to be accessed and modified by multiple threads. You'll need to provide more details on the use case to narrow down your options
I've done very similar thing recently as I have a list of languages in my app. I just use an Enum to do that. List of countries is fairly stable, so you shouldn't need to recompile this class to often;)

Lost in trying to make a sorting algorithm in Java

I'm lost trying to sort an array of AbstractEvents (which can be of type DailyEvent or WeeklyEvent). They can be sorted either using a DescriptionComparator class, a StartTimeComparator class or a EndTimeComparator class. Events are added to a Planner class in an array to make things simpler.
The planner class has a sort method that accepts an instance of one of the Comparator classes (which implement java's Comparator class) mentioned above. So now I need to figure out a way to sort these events but I'm fairly new to Java and don't get much of the lingo I've seen on certain sites. I'm looking for good old pseudocode with some explanation to know what I'm doing and learn from it.
Thanks to anyone who can help!
I am not sure what you want from the sorting .But I can give you a little bit of explanation.The comparator just gives a way to compare objects.For sorting you would be using utility classes like java.util.Arrays which has a sort method. So your Planner class has an array of Events which needs to be sorted. I guess you can use the Arrays.sort(arrayTobeSorted,comparator) inside the Planner class sort method. The comparator object given here would give the actual order of sorting. For example you have a DescriptionComparator which would sort objects based on description or StartTimeComparator which would sort based on start time.
Hope this helps.In Java there are many utility classes .So basic things like sorting are easy to do.

Categories