I have a nested treemap based on the following structure, and then it ofc continues from "2":{ with the same structure..
http://pastebin.com/uKwAVz5L
And as you can see, it is already sorted by the "c13" sub item (episode number).. but when i use the treemap in my applications, it shows up like this:
http://i50.tinypic.com/15o9vno.png
They are not even remotely sorted.. but i cant see why? :O
Its the same problem when using it in my android app..
Cheers
Here is some valuable infomation on TreeMap:
Red-Black tree based implementation of the SortedMap interface. This
class guarantees that the map will be in ascending key order, sorted
according to the natural order for the key's class (see Comparable),
or by the comparator provided at creation time, depending on which
constructor is used.
Note that the ordering maintained by a sorted map (whether or not an
explicit comparator is provided) must be consistent with equals if
this sorted map is to correctly implement the Map interface. (See
Comparable or Comparator for a precise definition of consistent with
equals.) This is so because the Map interface is defined in terms of
the equals operation, but a map performs all key comparisons using its
compareTo (or compare) method, so two keys that are deemed equal by
this method are, from the standpoint of the sorted map, equal. The
behavior of a sorted map is well-defined even if its ordering is
inconsistent with equals; it just fails to obey the general contract
of the Map interface.
Have you correctly implemented the methods mentioned above?
There are also different implementations of the Collections framework (An overview is here). If TreeMap doesn't provide the functionality you want you can implement another one and modify it to your needs.
Try using a Comparator:
TreeMap map = new TreeMap<Obj1, Obj2>(new ObjComparator());
private class ObjComparator() implements Comparator<Obj1> {
public int compareTo(Obj1 o1, Obj1 o2) {
return o1.compareTo(o2); // do your logic here
}
}
Related
A Comparator I used in my TreeMap broke the behavior I intended for that TreeMap. Look at the following code:
TreeMap<String, String> treeMap = new TreeMap<>(new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.toLowerCase().compareTo(o2.toLowerCase());
}
});
treeMap.put("abc", "Element1");
treeMap.put("ABC", "Element2");
What I think I have done is that I have created a map that is sorted by its keys, case-insensitive. The two distinct elements have non-equal keys (abc and ABC) whose comparison will return 0. I expected just a random ordering of the two elements. Yet, the command:
System.out.println("treeMap: " + treeMap);
resulted in:
treeMap: {abc=Element2}
The key abc has been re-assigned the value Element2!
Can anyone explain how could this happen and if it's a valid, documented behavior of TreeMap?
It happens because TreeMap considers elements equal if a.compareTo(b) == 0. It's documented in the JavaDoc for TreeMap (emphasis mine):
Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.
Your comparator isn't consistent with equals.
If you want to keep not-equal-but-equal-ignoring-case elements, put a second level of checking into your comparator, to use case-sensitive ordering:
public int compare(String o1, String o2) {
int cmp = o1.compareToIgnoreCase(o2);
if (cmp != 0) return cmp;
return o1.compareTo(o2);
}
The Comparator you pass to a TreeMap determines not just the ordering of the keys inside the Map, it also determines whether two keys are considered identical (they are considered identical when compare() returns 0).
Therefore, in your TreeMap, "abc" and "ABC" are considered identical keys. Maps don't allow identical keys, so the second value Element2 overwrites the first value Element1.
You need to ensure that the equality of that map's elements is consistent with the comparator. Quoting from the class comment:
Note that the ordering maintained by a tree map, like any sorted map,
and whether or not an explicit comparator is provided, must be
consistent with equals if this sorted map is to correctly
implement the interface.
The accepted answer is technically correct, but misses the idiomatic solution to the problem.
You should be using the static String.CASE_INSENSITIVE_ORDER comparator provided or at least using String.compareToIgnoreCase() inside your own to consider what is .equal().
For locale sensitive comparisons, you should use something from java.text.Collator
I know LinkedHashMap has a predictable iteration order (insertion order). Does the Set returned by LinkedHashMap.keySet() and the Collection returned by LinkedHashMap.values() also maintain this order?
The Map interface provides three
collection views, which allow a map's contents to be viewed as a set
of keys, collection of values, or set
of key-value mappings. The order of
a map is defined as the order in which
the iterators on the map's collection
views return their elements. Some map
implementations, like the TreeMap
class, make specific guarantees as to
their order; others, like the
HashMap class, do not.
-- Map
This linked list defines the iteration
ordering, which is normally the order
in which keys were inserted into the
map (insertion-order).
-- LinkedHashMap
So, yes, keySet(), values(), and entrySet() (the three collection views mentioned) return values in the order the internal linked list uses. And yes, the JavaDoc for Map and LinkedHashMap guarantee it.
That is the point of this class, after all.
Looking at the source, it looks like it does. keySet(), values(), and entrySet() all use the same entry iterator internally.
Don't get confused with LinkedHashMap.keySet() and LinkedHashMap.entrySet() returning Set and hence it should not guarantee ordering !
Set is an interface with HashSet,TreeSet etc beings its implementations. The HashSet implementation of Set interface does not guarantees ordering. But TreeSet does. Also LinkedHashSet does.
Therefore it depends on how Set has been implemented in LinkedHashMap to know whether the returning Set reference will guarantee ordering or not.
I went through the source code of LinkedHashMap, it looks like this:
private final class KeySet extends AbstractSet<K> {...}
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {...}
Thus LinkedHashMap/HashMap has its own implementation of Set i.e. KeySet. Thus don't confuse this with HashSet.
Also, the order is maintained by how the elements are inserted into the bucket. Look at the addEntry(..) method of LinkedHashMap and compare it with that of HashMap which highlights the main difference between HashMap and LinkedHashMap.
You can assume so. The Javadoc says 'predictable iteration order', and the only iterators available in a Map are those for the keySet(), entrySet(), and values().
So in the absence of any further qualification it is clearly intended to apply to all of those iterators.
AFAIK it is not documented so you cannot "formally" assume so. It is unlikely, however, that the current implementation would change.
If you want to ensure order, you may want to iterate over the map entires and insert them into a sorted set with an order function of your choice, though you will be paying a performance cost, naturally.
Like for a object to be inserted into a HashMap the object should implement the equals() and the hashcode() method(not necessarily).
Are there any special conditions for an object to be inserted in a TreeMap ?
Unless a Comparator which mutually compares the keys is provided in the TreeMap's constructor, the keys must implement Comparable.
See the javadocs on TreeMap constructors for more information: http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html
EDIT: As #MeBigFatGuy points out it is highly recommended for keys to override equals() as well, in such a way that the implementation is consistent with the comparison. From the TreeMap javadoc:
Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.
The type/class should (again, not necessarily) implement the Comparable interface (and override the compareTo method), so as to decide the ordering within the TreeMap.
There is a Java bean object which has implemented equals function based on certain criteria (Criteria A). I have a requirement to identify unique objects based on another criteria (Criteria B). Since the equals function uses criteria A, I can not use HashSet. So I thought of using TreeSet with my custom Comparator which is based on criteria B. My question is, Is it allowed to do like this? Any issues with this approach?
Thank you.
Here is some guide from Oracle Java:
Note that the ordering maintained by a
set (whether or not an explicit
comparator is provided) must be
consistent with equals if it is to
correctly implement the Set interface.
(See Comparable or Comparator for a
precise definition of consistent with
equals.) This is so because the Set
interface is defined in terms of the
equals operation, but a TreeSet
instance performs all key comparisons
using its compareTo (or compare)
method, so two keys that are deemed
equal by this method are, from the
standpoint of the set, equal. The
behavior of a set is well-defined even
if its ordering is inconsistent with
equals; it just fails to obey the
general contract of the Set interface.
I think in terms of technical, no, you don't have any problems. But, in terms of coding, readability and maintainability, you have to be careful, because other people can misuse or misunderstand what you are doing
If you perform search often and add elements rarely, consider keeping them in a List sorted by Criteria B and using Collections.binarySearch.
You can wrap them:
class BeanWrapper {
...
public boolean equals(Object other) {
return myBean.critB.equals(((Bean)other).critB);
}
}
And put them in the set like that.
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.