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

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.

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

Why can't I copy/convert a List<Set<String>> into a SortedMap<Set<String>,Integer>?

I want to copy my elements from a List<Set<String>> into a SortedMap<Set<String>,Integer>,
but I always get:
java.lang.ClassCastException: java.util.HashSet cannot be cast to java.lang.Comparable. (or HashMap could be a TreeSet too, vice versa)
Some places I've been reading say it isn't possible, but is this correct?
I can't believe I can't copy a original List or Set into a Map.
This is what I have tried:
List<Set<String> > tempnewOut= new ArrayList<>();
SortedMap<Set<String>,Integer> freqSetsWithCount= new TreeMap<>();
for (Set<String> set : tempnewOut)
{
freqSetsWithCount.put(set, 0);
}
The class that you use as a key in a TreeMap (one of the implementations of interface SortedMap) must either implement interface Comparable, or you must create the TreeMap by providing a Comparator to the constructor.
You're trying to use a HashSet<String> for the keys. HashSet doesn't implement Comparable, and you're not supplying a Comparator, so you get a ClassCastException.
One solution is to create the TreeMap by passing it a Comparator to the constructor. You'll have to implement the compare method of the Comparator to specify how the sets should be sorted in the map.
List<Set<String>> list = new ArrayList<>();
Comparator<Set<String>> comparator = new Comparator<Set<String>>() {
#Override
public int compare(Set<String> o1, Set<String> o2) {
// TODO: Implement your logic to compare the sets
}
};
SortedMap<Set<String>, Integer> set = new TreeMap<>(comparator);
// TODO: Fill the set
A SortedMap is, as the name implies, a Map of sorted elements. To be able to sort elements in this manner, the Comparable interface has to be implemented on the elements inside it.
The List of Sets that you're working with, doesn't implement the Comparable interface, so you aren't able to simply put the Set from your List inside the Set of your SortedMap without converting them to something that implements Comparable I'm afraid...
I'm not 100% sure, but I think the Set interface does not extend the Comparable interface. But in order to use an object as a Key in a sortedMap it needs to implement Comparable.
That's only logical, you cannot sort anything if you do not know if one instance is greater, equal or less than the other ...
Like the others I suggest you use the Integer as Key if that makes any sense.
SortedMap requires that the key ( your case the hashset) implements the comparable interface to sort it.
Hashset doesnt implement it so it cant to typecasted in the SortedMap implementation.
you could write you own Set which extends hashmap and implements comparable to make it work.
if you want to sort it by the integer simply switch the key and value
SortedMap<Integer,Set<String>>
the javadoc is pretty clear to me
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/SortedMap.html

Ordering of objects in 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.

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.

Categories

Resources