Ordering of objects in java - java

is there any way to sort the objects in java. I dont want to implement comparable interface or any other sorting algorithms.

You cannot sort things without (at least) using a sorting algorithm.
You also can't sort arbitrary objects, since Java provides no reliable ordering that will work for arbitrary objects. (See below.)
However, if your objects are instances of classes that support Comparable ... or you can implement a Comparator, then you can sort them, using:
Arrays.sort<T>(T[], Comparator<T>)
or
Arrays.sort<T extends Comparable>(T[])
In short, you have to implement Comparable or provide a Comparator. But if you do, the Java class library provides a good general-purpose sort algorithm that you can use.
The two obvious approaches for comparing incomparable objects won't work:
You could compare the results of their toString() methods. However, there's no guarantee that
a.toString().equals(b.toString()) IMPLIES a.equals(b)
You could compare their hashCodes, or their identity hashCodes, but hashcode equality does not imply object equality either.
It is theoretically possible to use reflection to access all of an object's fields, extract their values and compare them in some predictable sequence to give an ordering. This might work, but you'd end up with an ordering that was expensive to compute, that didn't make much sense, and was (if you weren't careful) inconsistent with equals(Object). So this sounds like a bad idea.

Sorting a collection of objects which don't themselves implement comparable can be achieved like this (assuming MyObject is the object you want to compare and sort):
List<MyObject> myList = new ArrayList<MyObject>();
// add MyObject instances to the list
Collections.sort(myList, new Comparator<MyObject>()
{
#Override
public int compare(MyObject o1, MyObject o2)
{
// perform your custom comparison of the two objects
// and return the result
}
})
But without any Comparator or Comparable implementation there's obviously no way you could sort a collection of objects.

Sort objects without a sorting algorithm? Hardly. In no language. What I am missing in your question is: "I want to avoid strict ordering criteria."

Code sample from java tutorials. This sample code doesn't implement sorting algorithm, what it is doing is that it is telling the Sort algorithm which field to sort the objects on. Since there can be many fields in an object this part is required.
import java.util.*;
public class EmpSort {
static final Comparator<Employee> SENIORITY_ORDER =
new Comparator<Employee>() {
public int compare(Employee e1, Employee e2) {
return e2.hireDate().compareTo(e1.hireDate());
}
};
// Employee database
static final Collection<Employee> employees = ... ;
public static void main(String[] args) {
List<Employee>e = new ArrayList<Employee>(employees);
Collections.sort(e, SENIORITY_ORDER);
System.out.println(e);
}
}
EDIT
The code sample here shows how same object collection sorted in different orders based on different fields.

Alternatively, ensure correct position when insertion, something like balanced-tree. Comparing is inevitable.

Related

Sorting objects inside arraylist

I have an ArrayList of some class type, in particular:
ArrayList<RowColElem<T>> myList = new ArrayList<RowColElem<T>>();
myList.add(new RowColElem(4,4,11));
myList.add(new RowColElem(1,1,11));
myList.add(new RowColElem(3,3,11));
myList.add(new RowColElem(1,0,11));
myList.add(new RowColElem(3,0,11));
The output right now is:
[(4,4,11),(1,1,11),(3,3,11),(1,0,11),(3,0,11)]
Is it possible to sort myList from ascending order with regard to both row and col? So the output would be:
[(1,0,11),(1,1,11),(3,0,11),(3,3,11),(4,4,11)]
And is it possible to sort the list inside the class where it's located rather than implementing Comparable or Comparator in **RowColElem** class?
Yes you can achieve this using Comparator methods. It is fairly neat in Java 8:
Collections.sort(myList,
Comparator.comparingInt(RowColElem::getRow).thenComparingInt(RowColElem::getCol));
This will compare using the rows and then, if they are equal, the columns. The Comparator interface has some pretty useful static and default methods - it's worth taking a good look at it.
You will have to implement the Comparable interface and your class RowColElement must provide the implementation of compareTo method, if you dont want to implement these interfaces you will have to extend ArrayList and will have to provide your own implementation. This is not a good idea, the best way will be to implement the interfaces and provide the custom comparison logic
If you want to keep your collection sorted as you insert new elements, you might want to consider using a TreeSet or another self-sorting structure instead of an ArrayList depending on your use case. These two structures will naturally keep themselves in sorted order when iterated over. Otherwise, you might have to implement your own SortedList class that does insertion sort transparently.
Either way, you'll have to implement Comparable<RowColElem<T>> on your class. It's fairly straight forward.
#Override
public int compareTo(RowColElem<T> o) {
int rowComp = Integer.compare(this.row, o.row);
if (rowComp == 0) {
return Integer.compare(this.column, o.column);
}
return rowComp;
}

where need to use collections.sort() and comparable and comparator interfaces in java collection?

I got some understanding of collections which gone through some articles.
But i 'm confusing where should implement collections.sort() method and where need to use comparable interface(compareTo() and comparator interface (compare()).
Comparable interface for compare this and another reference object but comparator for compare two objects.
I would like to know exactly which situation need to use methods ?
Thanks,
You should not implement Collections.sort(); this method is built-in to Java. Call that method without supplying a Comparator to sort by the natural order, if it's Comparable. Else, supply a Comparator to sort the Comparator's way.
You should have the class implement Comparable and provide a compareTo method if the class has a natural ordering, as indicated in the Comparable javadocs. An example would be for Integer and Double, which certainly have a natural mathematical ordering.
You should create a class that implements Comparator when you cannot make the class of the object to sort Comparable or when you want to present an ordering that is an alternative to the natural ordering, or when you want to impose an order when there is no natural ordering. An example would be to reverse the natural order (say, sort descending, from largest to smallest). Another example would be a data object with multiple fields, that you want to be sortable on multiple fields, e.g. a Person object with firstName and lastName: you could have a Comparator that sorts on lastName first, and another that sorts on firstName first.
Comparator makes sense to me when I don't have access to the code of the class I whish to compare: for instance, you may need to implement a custom comparator for String.
When I need to sort lists of my own custom objects, I write them to implement interface Comparable.
Let's see if I can explain it in plain words:
The compareTo() method is design to compare the active instance of an object with another instance of an object. So, let's say you have this example class:
public class Spam implements Comparable<Spam> {
private int eggs;
public Spam(int eggs) {
this.eggs = eggs;
}
public int compareTo(Spam otherSpam) {
return otherSpam.eggs - this.eggs;
}
public int getEggs() {
return eggs;
}
}
Let's say you use this Spam class somewhere in your code:
...
if(spam1.compareTo(spam2) == 0) {
System.out.println("Both spams are equal");
} else {
if(spam1.compareTo(spam2) > 0)
System.out.println("'spam2' is bigger than 'spam1'");
else
System.out.println("'spam2' is smaller than 'spam1'");
}
....
So, compareTo() is used to decide wether two instance of a class are equal, and, if they are not equal, which one is bigger.
The importance of this for a sorting algorithm is evident now. How would you sort a collection of objects if you don't know if one is bigger than another? When an implementation of sort is called, it uses the compareTo() method of the class to decide the correct order of the collection.
Finally, the compare() method is something you use when you want to perform the comparison outside the class. An implementation of this would be:
public int compare(Spam s1, Spam s2) {
return s1.getEggs() - s2.getEggs();
}
Hope this helps you
I guess Comparator is used only when you want to sort the objects in a class in the ascending order. Used to sort say the ID's of a class in ascending order. It is mutually exclusive sorting based on one field automatically rules out sorting based on another field

Removing duplicates without overriding hash method

I have a List which contains a list of objects and I want to remove from this list all the elements which have the same values in two of their attributes. I had though about doing something like this:
List<Class1> myList;
....
Set<Class1> mySet = new HashSet<Class1>();
mySet.addAll(myList);
and overriding hash method in Class1 so it returns a number which depends only in the attributes I want to consider.
The problem is that I need to do a different filtering in another part of the application so I can't override hash method in this way (I would need two different hash methods).
What's the most efficient way of doing this filtering without overriding hash method?
Thanks
Overriding hashCode and equals in Class1 (just to do this) is problematic. You end up with your class having an unnatural definition of equality, which may turn out to be other for other current and future uses of the class.
Review the Comparator interface and write a Comparator<Class1> implementation to compare instances of your Class1 based on your criteria; e.g. based on those two attributes. Then instantiate a TreeSet<Class>` for duplicate detection using the TreeSet(Comparator) constructor.
EDIT
Comparing this approach with #Tom Hawtin's approach:
The two approaches use roughly comparable space overall. The treeset's internal nodes roughly balance the hashset's array and the wrappers that support the custom equals / hash methods.
The wrapper + hashset approach is O(N) in time (assuming good hashing) versus O(NlogN) for the treeset approach. So that is the way to go if the input list is likely to be large.
The treeset approach wins in terms of the lines of code that need to be written.
Let your Class1 implements Comparable. Then use TreeSet as in your example (i.e. use addAll method).
As an alternative to what Roman said you can have a look at this SO question about filtering using Predicates. If you use Google Collections anyway this might be a good fit.
I would suggest introducing a class for the concept of the parts of Class1 that you want to consider significant in this context. Then use a HashSet or HashMap.
Sometimes programmers make things too complicated trying to use all the nice features of a language, and the answers to this question are an example. Overriding anything on the class is overkill. What you need is this:
class MyClass {
Object attr1;
Object attr2;
}
List<Class1> list;
Set<Class1> set=....
Set<MyClass> tempset = new HashSet<MyClass>;
for (Class1 c:list) {
MyClass myc = new MyClass();
myc.attr1 = c.attr1;
myc.attr2 = c.attr2;
if (!tempset.contains(myc)) {
tempset.add(myc);
set.add(c);
}
}
Feel free to fix up minor irregulairites. There will be some issues depending on what you mean by equality for the attributes (and obvious changes if the attributes are primitive). Sometimes we need to write code, not just use the builtin libraries.

Is there anyway to add metadata to Java Collections?

Let's say I have a collection of objects which can be sorted using a number of different comparators based on the different fields of the object.
It would be nice to be able to know later on in the code which comparator was used to sort the Collection with and if it was ascending or descending. Is there anyway to do this elegantly instead of using a bunch of Booleans to keep track of things?
Not for the Collection interface, but if you use a SortedSet there's a comparator() method where you can ask for its comparator.
Otherwise you'll have to subclass the collection class you're using to add the accessors you need.
No there's nothing with the implementations that does this. You would need to track it yourself. You could subclass a Collection implementation to add fields which hold this information.
You could also map the implementations to metadata as you like with a Map -- in particular it seems like you want IdentityHashMap to do this, since you don't want two different collections to be compared for equality as keys with equals().
I would store a boolean (ascending/descending), and a reference to the Comparator used to sort, if that's what completely determines the sort. Or if it's sorted on field, store a String naming the field perhaps.
sure:
define methods for your decorated Collection<Foo>
public List<Comparator<Foo>> getComparators() { ... }
and
public int whichComparator() { ... }
that returns which Comparator is currently in use from the List. You could make it fancier with a Map and some sensible keys (say, enums - perhaps even enums which implement the comparators) if you're modifying which comparators might be used over the life of the object, but I think the above is a good enough start.

Java: SortedMap, TreeMap, Comparable? How to use?

I have a list of objects I need to sort according to properties of one of their fields. I've heard that SortedMap and Comparators are the best way to do this.
Do I implement Comparable with the class I'm sorting, or do I create a new class?
How do I instantiate the SortedMap and pass in the Comparator?
How does the sorting work? Will it automatically sort everything as new objects are inserted?
EDIT:
This code is giving me an error:
private TreeMap<Ktr> collection = new TreeMap<Ktr>();
(Ktr implements Comparator<Ktr>). Eclipse says it is expecting something like TreeMap<K, V>, so the number of parameters I'm supplying is incorrect.
The simpler way is to implement Comparable with your existing objects, although you could instead create a Comparator and pass it to the SortedMap.
Note that Comparable and Comparator are two different things; a class implementing Comparable compares this to another object, while a class implementing Comparator compares two other objects.
If you implement Comparable, you don't need to pass anything special into the constructor. Just call new TreeMap<MyObject>(). (Edit: Except that of course Maps need two generic parameters, not one. Silly me!)
If you instead create another class implementing Comparator, pass an instance of that class into the constructor.
Yes, according to the TreeMap Javadocs.
Edit: On re-reading the question, none of this makes sense. If you already have a list, the sensible thing to do is implement Comparable and then call Collections.sort on it. No maps are necessary.
A little code:
public class MyObject implements Comparable<MyObject> {
// ... your existing code here ...
#Override
public int compareTo(MyObject other) {
// do smart things here
}
}
// Elsewhere:
List<MyObject> list = ...;
Collections.sort(list);
As with the SortedMap, you could instead create a Comparator<MyObject> and pass it to Collections.sort(List, Comparator).
1.
That depends on the situation. Let's say the object A should sort before the object B in your set. If it generally makes sense to consider A less than B, then implementing Comparable would make sense. If the order only makes sense in the context in which you use the set, then you should probably create a Comparator.
2.
new TreeMap(new MyComparator());
Or without creating a MyComparator class:
new TreeMap(new Comparator<MyClass>() {
int compare(MyClass o1, MyClass o2) { ... }
});
3. Yes.
Since you have a list and get an error because you have one argument on the map I suppose you want a sorted set:
SortedSet<Ktr> set = new TreeSet<Ktr>(comparator);
This will keep the set sorted, i.e. an iterator will return the elements in their sort order. There are also methods specific to SortedSet which you might want to use. If you also want to go backwards you can use NavigableSet.
My answer assumes you are using the TreeMap implementation of SortedMap.
1.) If using TreeMap, you have a choice. You can either implement Comparable directly on your class or pass a separate Comparator to the constructor.
2.) Example:
Comparator<A> cmp = new MyComparator();
Map<A,B> map = new TreeMap<A,B>(myComparator);
3.) Yes that's correct. Internally TreeMap uses a red-black tree to store elements in order as they are inserted; the time cost of performing an insert (or retrieval) is O(log N).
You make a Comparator<ClassYouWantToSort>. Then the Comparator compares the field that you want to sort on.
When you create the TreeMap, you create a TreeMap<ClassYouWantToSort>, and you pass in the Comparator as an argument. Then, as you insert objects of type ClassYouWantToSort, the TreeMap uses your Comparator to sort them properly.
EDIT: As Adamski notes, you can also make ClassYouWantToSort itself Comparable. The advantage is that you have fewer classes to deal with, the code is simpler, and ClassYouWantToSort gets a convenient default ordering. The disadvantage is that ClassYouWantToSort may not have a single obvious ordering, and so you'll have to implement Comparables for other situations anyway. You also may not be able to change ClassYouWantToSort.
EDIT2: If you only have a bunch of objects that you're throwing into the collection, and it's not a Map (i.e. it's not a mapping from one set of objects to another) then you want a TreeSet, not a TreeMap.

Categories

Resources