Best Place to Put a Comparator - java

I am sorry if I am asking something that has been answered already but I could not find a reference. My question is where is the best place to put a comparator which layer does it belong to.For example I need a list of User Objects sorted by users date of birth then surname and then first name.

If the comparator is intrinsic to the object (e.g. it's the only way of ordering it that makes sense), then I would just implement Comparable on the object.
If the comparator is one of many (e.g. a Comparator instance), and only makes sense in a particular context, then I'd place the comparator class in that layer.

In your case if would put it on the domain class and sort it in the dao during fetch meaning have two methods(or more based on Comaprision types) on dao one to just get a list of unsorted object e.g. getUsers() and one method for sorted list e.g getSortedUers(); ofcourse you can only have a sorted method but always calling a sort is an over head if no sort is required.

If you are using database, then best way is to sort it in query itself, using order by

The general answer would be: put it where it is most required :-)
This depends a lot on your actual design and architecture. In general, either you can put it next to your user object, or into the layer which uses it most (or exclusively).

Yeah, if you use database or some external service and it's possible to sort there it's best way. But if you need to sort objects in your application it depends on your architecture. There are 2 variants. If you need sort only once - create anonymous class then you won't store reference on this object. If you need to make sort several times you can store it as static field of class or a non-static field.

Related

Passing arguments to java function in bulk

What would you use if you wanted to pass a list of options into a function?
For example, if you have an interface to a server:
public interface Server {
public void authUser(String username, String password, <xyz> options);
}
What structure would use use for to pass a set of options? Something like a HashMap?
The reason I'm saying that it comes from tunnel vision is because I feel that this goes against Java standards. Java has method overloading. So if I get flames for raising the question I understand. But overall, maybe in different cases, would you ever pass bulk data in some collection and, if yes, which one?
Option1 : If you are choosing any collections like List or Set these are specific to an object . I mean,
Lets Assume, Set sets = new HashSet();
If I want 5 Object of different different class having no relationship to be send, then It would be very difficult to recognize that which Object is belong to which class while Iteration. So, I wont recommend Collections.
Option2 : If you are choosing Map, the same above problem may occurs while getting the Object Dynamically. So, This Options is also not recommended.
Option3 :
Why cann't you create your own DTO and in that DTO place your reqyired datastructure and pass it over.
If you want 5 different Object to be pass then, you can pass. If all are of same type then you may use Collection or array or Variable Arguement based on your scenerio.
I think anything Serializable is exactly the thing. If you can serialize the object, then you can pass (store, transmit...) it, passing it's properties in bulk. What format of serialized data to choose, is another question.
It depends on the data you want to pass.
You can use a map(hashmap) if you are passing key-value pairs.
If it is just a list of diffrent object, you can use List(ArrayList)
Other option is to create DTO(data transfer object) with getter and setter methods.
You may want to take a look at VARARGS feature that was introduced in JAVA5.
I'd suggest a Map [HashMap] as you can then access the argument values via their Keys.

Best collection to store student details?

Hey im making a store for student details and i wanted some opinions on which collection to use. The store will have details such as name, number, address and email. The store will then be printed to a text file where i can load, save, edit and delete the details in the text file. I have never done this before and i do not no if there is any restrictions to file I/O when using collections. So i would really appreciate the comments. Thanks in advance.
If I were at your place,
then i would have created a bean class say Student and for collection ArrayList<Student> student = new ArrayList<Student>(); and as ArrayList is serialized so no issue for disk writing and a class for all IO operations.
For sorting ArrayList by object property look
Unless some special "fast location" capabilities are required, such as search by last name or by student ID, a list would be an appropriate collection to use.
List<Student> students = new ArrayList<Student>();
If you do need to organize your students by some attribute, say, by student ID, consider using LinkedHashMap:
Map<String,Student> studentById = new LinkedHashMap<String,Student>();
LinkedHashMap gives you a predictable order of iteration. You could use a regular HashMap<K,V>, but the order of iteration will be arbitrary. Finally, you could use a TreeMap<K,V>, which would base the order of iteration on the ordering of the keys.
Well if it has to be serializable, i.e. meaning you can write it to disk, you can use a List. Now before anyone screams you can't serialize a List that is correct, but you also cannot instantiate a List either. Since we know all known subclasses of List are serializable you can safely cast. In terms of how to store the data List<Student> should be just fine.
EDIT
There seems to be some confusion here. In Object Oriented languages we know that the is-a relationship holds true for objects specified in a hierarchy. So in the Java API we have an interface called List this interface has classes that implement it ArrayList for instance. This puts ArrayList in the hierarchy of List. Since ArrayList implements Serializable and we know that you cannot instantiate an object marked with the keyword interface (in Java). We can use casting to Serialize any known implementation of List. The reason why this will work is that the implementation (i.e. concrete object) that is passed around is guaranteed to be serializable.
In the simplest case a java.util.List will do exactly what you want. However, if you want to be able to find entries in the collection quickly ( to support your update requirements ), you should also probably look at java.util.Map. Map allows you to navigate quickly to a particular record without having to iterate over the entire collection, whereas with a List you'd have to look at every student in the collection in turn until you find the one you are interested in.

Java map content comparison

Here is a tricky data structure and data organization case.
I have an application that reads data from large files and produces objects of various types (e.g., Boolean, Integer, String) that are categorized in a few (less than a dozen) groups and then stored in a database.
Each object is currently stored in a single HashMap<String, Object> data structure. Each such HashMap corresponds to a single category (group). Each database record is built from the information in all the objects contained in all categories (HashMap data structures).
A requirement has appeared for checking whether subsequent records are "equivalent" in the number and type of columns, where equivalence must be verified across all maps by comparing the name (HashMap key) and the type (actual class) of each stored object.
I am looking for an efficient way of implementing this functionality, while maintaining the original object categorization, because listing objects by category in the fastest possible way is also a requirement.
An idea would be to just sort the keys (e.g., by replacing each HashMap with a TreeMap) and then walk over all maps. An alternative would be to just copy everything in a TreeMap for comparison purposes only.
What would be the most efficient way of implementing this functionality?
Also, if how would you go about finding the difference (i.e., the fields added and those removed), between successive records?
Create a meta SortedSet in which you store all the created maps.
Means SortedSet<Map<String,Object>> e.g. a TreeSet which as a custom Comparator<Map<String,Object>> which does check exactly your requirements of same number and names of keys and same object type per value.
You can then use the contains() method of this meta set structure to find out if a similar record does already exist.
==== EDIT ====
Since I've misundertood the relation between database records and the maps in the first place, I've to change some semantics my answer now of course a little bit.
Still I'would use the mentioned SortedSet<Map<String,Object>> but of course the Map<String,Object> would now point to that Map you and havexy suggested.
On the other hand could it be a step forward to use a Set<Set<KeyAndType>> or SortedSet<Set<KeyAndType>> where your KeyAndType will only contain the key and the type with appropriate Comparable implementation or equals with hashcode.
Why? You asked how to find the differences between two records? If each record relates to one of those inner Set<KeyAndType> you can easily use retainAll() to form the intersection of two successive Sets.
If you would compare this to the idea of a SortedSet<Map<String,Object>>, in both ways you would have the logic which differenciates between the fields within the comparator, one time comparing inner sets, one time comparing inner maps. And since this information gets lost when the surrounding set is constructed, it will be hard to get the differences between two records later on, if you do not have another reduced structure which is easy to use to find such differences. And since such a Set<KeyAndType> could act as key as well as as easy base for comparison between two records, it could be a good candidate to be used for both purposes.
If furthermore you wanna keep the relation between such a Set<KeyAndType> to your record or the group of Map<String,Object> your meta structure could be something like:
Map<Set<KeyAndType>,DatabaseRecord> or Map<Set<KeyAndType>,GroupOfMaps> implemented by a simple LinkedHashMap which allows simple iteration in original order.
One soln is to keep both category based HashMap and combined TreeMap. This will have slight more memory requirement, not much though, as you ll just keep the same reference in both of them.
So whenever you are adding/removing to HashMap you will do the same operation in the TreeMap too. This way both will always be in sync.
You can then use TreeMap for comparison, whether you want comparison of type of object or actual content comparison.

Using annotation for an object sorter?

I am working a container to hold a list of objects (of the same class) the have certain fields that use a custom RetentionSortable annotation. The purpose of the annotation is two fold:
To mark the field as able to be compared to another objects same field.
And to give the sort name of the field (eg. Modification Date or First Name).
The container will then walk through the list of objects (remember they are like) and gather the list of RententionSortable's that the object contains and pass the list to the GUI. The GUI will display the list and request a sortable selection and return it to the sortable which will then sort the list based on the RetentionSortable selected.
The purpose of this method or sorting object is to allow me to create a small container that can generically accept any object and sort it as long as it has at least one RetentionSortable field.
My gut screams that this is bad practice and that relying this much on reflection is a bad idea but my tests work flawlessly and better than I expected.
Is using annotation reflection to find all the fields that are annotated by a particular annotation good practice for abstract object sorting?
Annotations are there for convenience, and your use is making the situation more convenient, so it seems reasonable. The alternative is to maintain a separate dictionary of which fields are sortable for which objects, and is slightly more cumbersome but slightly better from a seperation of concerns point of view.
The question is really whether your object should know about the annotations or not (is the object going to be reused in another situation where the annotations do not make sense or conflict). With a separate list of sortable fields, you can pick which to apply in any given case.
If the convenience trade-off works for you, then you should stick with the annotations, just so long as you are aware of the potential design ramifications (which may be nothing for your particular case).
How do you think basically every annotation-driven configuration framework works? "Give me all the of such-and-such type fields annotated with '#Inject'" or "give me everything in package baz.plugh annotated with '#Controller'".
Whether or not it's good for "abstract sorting" or not, I don't see why not. If it works, and eliminates the need for things like bean mappers and bean info classes, what's the issue?

structure for holding data in this instance (Hashmap/ArrayList etc)?

Best way to describe this is explain the situation.
Imagine I have a factory that produces chairs. Now the factory is split into 5 sections. A chair can be made fully in one area or over a number of areas. The makers of the chairs add attributes of the chair to a chair object. At the end of the day these objects are collected by my imaginary program and added into X datatype(ArrayList etc).
When a chair is added it must check if the chair already exists and if so not replace the existing chair but append this chairs attributes to it(Dont worry about this part, Ive got this covered)
So basically I want a structure than I can easily check if an object exists if not just straight up insert it, else perform the append. So I need to find the chair matching a certain unique ID. Kind of like a set. Except its not matching the same object, if a chair is made in three areas it will be three distinct objects - in real life they all reperesent the same object though - yet I only want one object that will hold the entire attribute contents of all the chairs.
Once its collected and performed the update on all areas of the factory it needs iterate over each object and add its contents to a DB. Again dont worrk about adding to the DB etc thats covered.
I just want to know what the best data structure in Java would be to match this spec.
Thank you in advance.
I'd say a HashMap: it lets you quickly check whether an object exists with a given unique ID, and retrieve that object if it does exist in the collection. Then it's simply a matter of performing your merge function to add attributes to the object that is already in the collection.
Unlike most other collections (ArrayList, e.g.), HashMaps are actually optimized for looking something up by a unique ID, and it will be just as fast at doing this regardless of how many objects you have in your collection.
This answer originally made reference to the Hashtable class, but after further research (and some good comments), I discovered that you're always better off using a HashMap. If you need synchronization, you can call Collections.synchronizedMap() on it. See here for more information.
I'd say use ArrayList. Override the hashcode/equals() method on your Chair object to use the unique ID. That way you can just use list.contains(chair) to check if it exists.
I'd say use an EnumMap. Define an enum of all possible part categories, so you can query the EnumMap for which part is missing
public enum Category {
SEAT,REST,LEGS,CUSHION
}

Categories