TreeMap and LinkedHashMap classes [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I found a Java question J couldn't understand what should be answer
The TreeMap and LinkedHashMap classes:
enable iteration of a map's entries based on the insertion order of elements only.
enable iteration of a map's entries based on natural ordering of keys only.
enable iteration of a map's entries in a deterministic order.
enable iteration of a map's entries based either natural ordering of keys OR natural ordering of values depending on the arguments sent to the contructor.

In Java:
TreeMap is a Map that automatically sorts the Map entries according to its natural ordering using Comparable<T> interface
LinkedHashMap is Map that guarantees that the entries will be returned in the same order as they were added

Related

Interview Question - Data structure performing CRUD operation in O(1) time and maintaining insertion order [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
Recently I have attended an interview as backend developer, and I've been asked one the following question:
Design a data structure that can perform insert, update, remove, and
contains operation in O(1) time complexity.
It should allay printing all the elements in O(n) time maintaining the insertion order of
elements.
Can someone please explain which data structure we can use and how that data structure allows to achieve the required O(1) time complexity?
It seems like your interviewer was talking about a composite data structure which combines a Linked list and a Hash table.
And JDK offers and implementation of such data structure in the form of LinkedHashMap, which is basically a combination of a HashMap and a LinkedList. It's methods almost as fast as HashMap's ones.
LinkedHashMap capable to perform these operations in amortized O(1) time (only if the Key has a proper hash-function, the worst case would be O(n)):
insertion via put(key, value);
containsKey(key) check;
updating the value of via replace(key, value) and replace(key, oldValue, newValue);
retrieve the values with get(key);
And owing to a LinkedList maintained under the hood is, LinkedHashMap can can track the insertion order of entries (updating the value of an existing entry has no impact on the order).
Here's a quote from the documentation:
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

Why is adding an entry set as parameter to addall method a bad practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 months ago.
Improve this question
Why is the following code a bad practice and what is the solution for it?
TreeSet<Map.Entry<Integer, Map<String, String>>> sortedtable = new TreeSet<>(new ComparatorByDueDate());
public void sortTable(Map<Integer, Map<String, String>> table){
sortedtable.addAll(table.entrySet());
}
Update: As per Sonar, it is a bad practice. I am asking the question here as the sonar explanation seems confusing.
Java Map.Entry objects are not intended for long term storage. From the docs (emphasis mine),
A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.
If anyone, for any reason, adds, removes, or modifies any part of the map after the fact, then your TreeSet entries now have undefined behavior. They might still be good, they might get nulled out, they might exhibit some random behavior.
If you want to store a pair of elements, then write a class that has two instance variables. If you're on a new enough Java version, then records are great for this sort of thing.

How do Treemaps handle collisions in java? [duplicate]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I have the below code for tree map where I store duplicate key and it seems overwrite the existing one.
TreeMap<String, Integer> tm=new TreeMap<>();
tm.put("vivek", 1);
tm.put("vivek", 2);
System.out.println(tm);
It prints {vivek=2} So it means map allow to overwrite on key basis?
All maps share the same basic properties, one of which is that all keys must be unique. Hence why keySet() returns a Set.
To do what you are looking for you need a Multimap - which is essentially a Map to a List.
Map<Integer, List<String>> multiMap;
To add an object get the list for that key, if it is null add a list then add your value to the list, otherwise just add your value to the existing list.
There are some multimap implementation available in various 3rd party libraries or it's easy enough to implement your own.
TreeMap#public V put(K key, V value) API says
Associates the specified value with the specified key in this map.
If the map previously contained a mapping for the key, the old value is replaced.

Why doesn't LinkedHashSet implement List? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
To my understanding, a List is an ordered collection of items. And a Set is a collection of unique items.
Now my question is, why does LinkedHashSet, which describes an ordered collection of unique items, implement the Set interface (=> unique), but not the List interface (=> ordered)?
One possible argument is that List is intended for random access datastructures, but that would be invalidated by the fact that LinkedList doesn't have "true" random access either. In fact, LinkedHashSet is backed by an internal linked list. Also the documentation for List says otherwise:
Note that these [positional index] operations may execute in time proportional to the index value for some implementations.
If it implemented a List you would be able to use it as a List:
List list = new LinkedHashSet();
This might lead to issues with duplicates which don't appear in Set but are allowed in List.
In other words, you shouldn't declare that something is a List when it doesn't allow duplicates even if it holds the order and allows adding, getting, removing and checking the size.
Unlike sets, lists typically allow duplicate elements
--List documentation
because LinkHashSet is class which implements set interface . List and Set has its own functionality List allowed duplicates while set do not allowed duplicates but if you want linear order insertion in a HastSet then LinkedHashSet is used with no duplicates in itself ..
Set s = new LinkedHashSet();
is the implementation of a set in which insertion order is preserved and duplicates do not allowed..

Does the JVM create background threads when updating a HashMap, such that a HashSet of its keys may be 'out of date' in a single threaded program? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a HashSet which contains the keys of a HashMap, and update the contents of the HashMap, adding a new key in the process. After I've done this, I then want to use the HashSet of keys again, since I know that they kept up to date with the keys of the HashMap. I just want to make sure that this is all done by the same thread, and that there is no concurrency going on here that I might be unaware of, such that I tell the HashMap to add the new entry, and before it has updated I have used the HashSet information while it is out of date.
In code:
HashMap<String, Integer> myHashMap = new HashMap<String, Integer>();
HashSet<String> myHashSet = myHashMap.keySet();
... processing ...
myHashMap.put(new_key, value);
... use the **original** HashSet of keys, myHashSet ...
Could the above situation occur, given that this is the only thread created by the programmer, such that myHashMap and myHashSet would be out of sync? I'm not talking about the programmer creating more than one thread - the main program runs in a single thread (see above).
No they won't because the key set is a view onto the actual keys in the HashMap.
From the Javadocs:
The set is backed by the map, so changes to the map are reflected in
the set, and vice-versa.
And you can see the same in OpenJDK's implementation of HashMap.
So for a single-threaded program these should always be in sync.
The Java collections classes don't do things with threads internally because it would make using them too difficult and error prone. They leave the threading model to the calling code and just provide guarantees (or otherwise) about which operations are thread-safe.

Categories