-3

According to this link in Java 8, to avoid collisions in map (HashMap, LinkedHashMap, and ConcurrentHashMap) are implemented using balanced trees instead of LinkedList.

Then what is the difference if:

  1. Both (TreeMap and Other Maps (HashMap, LinkedHashMap, and ConcurrentHashMap) got implemented using self-balancing-trees, as worst case accessibility is same.
  2. Sorting of entry I can achieve as follows:

    public <K extends Comparable,V extends Comparable> LinkedHashMap<K,V> sortByKeys(LinkedHashMap<K,V> map){
        List<K> keys = new LinkedList<K>(map.keySet());
        Collections.sort(keys, (Comparator<? super K>) new Comparator<String>() {
            @Override
            public int compare(String first, String second) {                
                return first.compareTo(second);
            }
        });
    }
    

Apart from sorting and accessbility what are the other properties of TreeMap?

Ramesh Papaganti
  • 7,311
  • 3
  • 31
  • 36
  • This isn't a good question for stackoverflow, TreeMaps are for when you need a Map that is sorted automatically (e.g. a dictionary) which you already seem to know. – Daniel Bickler Apr 03 '17 at 16:51
  • 4
    What is your point? In #1 you're implying that there is no difference because *worst case* is the same. That's very pessimistic of you, assuming you'll always have *worst case*. In #2, you say you can always sort the keys when needed, but sorting is expensive. A `TreeMap` is always sorted, so if `Map` is continually modified, and you continually needs result in order, there is a *huge* performance difference. `HashMap` performs better (assuming modicum hash function) and doesn't require keys to be *comparable*. `TreeMap` is better if keys are required to be in order. – Andreas Apr 03 '17 at 16:52
  • 2
    ... Besides, `TreeMap` can give you neighboring keys to a given key value, whether key value is in the map or not. A `HashMap` can't do that. And a sorted list cannot do that, unless you then perform a binary search *after* wasting time sorting the list first. – Andreas Apr 03 '17 at 16:57
  • @Andreas As entry objects are always balanced , accessibility is `logn`. If is it not true in all cases. Can you please provide any scenario. – Ramesh Papaganti Apr 03 '17 at 17:00
  • what is the wrong in the question. I am not getting why down votes. – Ramesh Papaganti Apr 03 '17 at 17:02
  • 1
    No idea what you mean by "As entry objects are always balanced", or what scenario you are asking about. – Andreas Apr 03 '17 at 17:02
  • 3
    What is the question? – Holger Apr 03 '17 at 17:05
  • 1
    Please refer this link : http://openjdk.java.net/jeps/180 – Ramesh Papaganti Apr 03 '17 at 17:06
  • 3
    The fact that java 8 changed HashMaps to use a balanced tree for collisions is purely a **performance booster**, changing performance from _O(n)_ to _O(_ log _n)_ for *collissions*. It has no functional meaning/impact whatsoever. Your entire question seems based on assumption of the change having functional meaning, and is so misguided that the question is meaningless, and hence all the down-votes. If you have question about `HashMap` vs `TreeMap`, then ask that, but it still has nothing to do with the performance improvement implemented in Java 8. – Andreas Apr 03 '17 at 17:06
  • 1
    ... As the link provided by @RameshPapaganti says: ***Improve the performance** of `java.util.HashMap` **under high hash-collision conditions** by using balanced trees rather than linked lists to store map entries. Implement the same improvement in the `LinkedHashMap` class.* – Andreas Apr 03 '17 at 17:08
  • 1
    “sorting and accessibility” are technical properties, not “use cases”, so it’s entirely unclear, what you are asking about, properties or use cases. If you are “asking” about “sorting and accessibility”, well these are the fundamental differences, which you just wrongly dismissed, so there is no actual question left. – Holger Apr 03 '17 at 17:39
  • @Andreas Lets say we have 100 `TreeNodes` with same key, but different values. 1 . Accessibility :: In this scenario All `TreeNodes` are balanced. if call `.get()` method the time complexity is `log(n)` . The same is true in `TreeMap`. – Ramesh Papaganti Apr 03 '17 at 17:49
  • 1
    You never have 100 `TreeNodes` with same key. It’s a fundamental property of all maps, that the keys are *unique*. If you try to store 100 identical keys, you’ll have exactly one key. Besides that, it still makes no sense to try to conclude from corner cases to the general case. The average time complexity of `HashMap.get` is `O(1)`, not `O(log(n))`. – Holger Apr 03 '17 at 18:13
  • @Holger I mean same `hashcode` with different `values`. Please see what i mean exactly . http://stackoverflow.com/questions/19691920/collision-resolution-in-java-hashmap – Ramesh Papaganti Apr 03 '17 at 18:31
  • 1
    @RameshPapaganti what you probably mean, is that you have a single `TreeNode` with 100 entries in it and you need to search for the deepest one in that tree. In this case the search will indeed take `O(log(n))`, but this is the worst case scenario. If you look at the average in a map, where you have buckets that are both Trees and Linked Nodes, the complexity of a get will be `O(1)`. – Eugene Apr 03 '17 at 18:33
  • @Holger I am worrying about worst case. In both (`Treemap` , `HashMap`) worst case time complexity is same. Is there any other properties or use cases which which differentiate `TreeMap` and `HashMap` in `java8`. Here i mentioned only accessibility. – Ramesh Papaganti Apr 03 '17 at 18:47
  • 2
    @RameshPapaganti Why are you so focused on *worst case*? If you truly have a map with 100+ keys (and remember, keys are unique, cannot be the same) and *every* key in the map has the exact same hash code, then your hashing algorithm is flawed, and you should fix it, rather than think about `HashMap` vs `TreeMap`. – Andreas Apr 03 '17 at 21:11
  • 1
    @RameshPapaganti: the worst case of `HashMap` is `O(n)`, which is relevant only when the hashcodes are the same and the keys are not comparable. That can’t be related to `TreeMap` at all, as `TreeMap` doesn’t support uncomparable keys at all. – Holger Apr 04 '17 at 08:02

1 Answers1

0
  1. Both (TreeMap and Other Maps (HashMap, LinkedHashMap, and ConcurrentHashMap) got implemented using self-balancing-trees, as worst case accessibility is same.

    In jdk7 and old jdk recalculate bucket index when size >= threshold,and each bucket impelements as a linked list, but in jdk8 that is adjust the balancing-trees and each bucket impelemented as a Red-Black Tree.

    there is only one bucket when put something like this into HasMap in jdk7. then lookup node is O(N).

    class Foo{
       int hashCode(){
           return 0;
       }
    }
    Foo first=new Foo();
    Foo last=new Foo();
    map.put(first,"anything");
    map.put(last,"anything");
    map.get(last | first);// O(N)
    

    there is only one bucket when put something like this into HasMap in jdk8 but the key implemented Comparable. then lookup node is O(log(N)), however lookup node will be fallback to O(N) if i are identical.

    class Foo implements Comparable<Foo> {
        private int i;
    
        public Foo(int i) {
    
            this.i = i;
        }
    
        public int hashCode() {
            return 0;
        }
    
        @Override
        public int compareTo(Foo that) {
            return i - that.i;
        }
    }
    
    Foo first=new Foo(1);
    Foo last=new Foo(2);
    map.put(first,"anything");
    for(int i=2;i<threshold;i++)
      map.put(new Foo(i + 1), "anything");
    map.put(last,"anything");
    map.get(last | first);// O(log(N))
    
  2. sort a LinkedHashMap you can create a TreeMap instance instead, since Map.keySet() returns unordered set not a list so you can't sort the map via sort its keys.

    public <K extends Comparable<? super K>, V> Map<K, V> sortByKeys(Map<K, V> map) {
     return new TreeMap<K, V>(map);
    }
    
holi-java
  • 29,655
  • 7
  • 72
  • 83
  • @Holger please help me look at this answer whether is right? thanks first. – holi-java Apr 04 '17 at 14:57
  • The new `HashMap` implementation still resizes/rehashes the table when the size exceeds the threshold (loadfactor*size). It also still uses a linked list (don’t write it like the typename `LinkedList`) when the number of elements per buckets is below a threshold. When the threshold is exceeded, a balanced tree will be created which uses the hash code first, so bucket collisions with different hash codes are sorted out, whether the keys are comparable or not. Only for truly identical hash codes, it will try to uses the natural order, if there is one. – Holger Apr 05 '17 at 11:57
  • There is still the possibility that a) `compareTo` returns zero but `equals` returns `false` (change `last=new Foo(2)` to `last=new Foo(1)`) or b) the keys are not `Comparable`, in which case the map will basically fall back to a linked list with `O(n)` lookup. However, it must be emphasized that for the `O(log(n))` of the tree lookup, `n` is the bucket population and for the `O(n)` of the fallback, `n` is the number of objects with identical hash code, not having a `<` or `>` relation, so `n` is not equal to the size of the `HashMap`. – Holger Apr 05 '17 at 12:03
  • In your example with only two keys, there will never be a tree node anyway… – Holger Apr 05 '17 at 12:05
  • In the second part, the method should be `public , V> Map sortByKeys(Map map) { return new TreeMap<>(map); }`. 1) `K extends Comparable` referers to the raw type `Comparable`. 2) there is no point in narrowing the parameter type to `LinkedHashMap`; any `Map` will do and the result order is determined by the `TreeMap`, whether the input map has an order or not. – Holger Apr 05 '17 at 12:12
  • @Holger you are right, My expression ability is so bad. I want to convey something what you has said. – holi-java Apr 05 '17 at 14:22