How to take separate data from LinkedHashMap<String, Double> in Java - java

I used LinkedHashMap<String, Double> . I want to take separate values from it. If it is Array we can use .get[2] ,.get[5] etc. for take 2nd and 5th value. But for LinkedHashMap<String, Double> how to do it. I used following code. But it print all the values contained in LinkedHashMap<String, Double>. I need to take separately.
Set set = mylist.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me1 = (Map.Entry)i.next();
System.out.print(me1.getKey());
System.out.println(me1.getValue());

You may use the LinkedHashMap#get(Object key) method
Which will return the value corresponding to the key parameter. Since your keys are String, you can not use an int to retrieve them.
Example
If your LinkedHashMap contains ["key", 2.5], calling
System.out.println(lnkHashMap.get("key"));
will print
2.5
Addition
If you're using java-8, there is a workaround using a Stream object.
Double result = hashmap.values()
.stream()
.skip(2)
.findFirst()
.get();
This will skip the two first values and get to the third one directly and return it.
If not, here is a solution
public <T> T getValueByIndex (Map<? extends Object, T> map, int index){
Iterator<T> it = map.values().iterator();
T temp = null;
for (int i = 0 ; i < index ; i++){
if (it.hasNext()){
temp = it.next();
} else {
throw new IndexOutOfBoundsException();
}
}
return temp;
}

It could be the case that you are using the wrong data structure for your purpose.
If you look closely to the LinkedHashMap API you will notice that it is indeed a Map and the only way to access a previously stored value is by providing its key.
But if you really think you need to access the ith value of the LinkedHashMap according to its insertion-order (or access-order) you can use a simple utility method like the following:
Java 8 Solution
private static <K, V> Optional<V> getByInsertionOrder(LinkedHashMap<K, V> linkedHashMap, int index) {
return linkedHashMap.values().stream()
.skip(index)
.findFirst();
}
Java 7 Soution
private static <K, V> V getByInsertionOrder(LinkedHashMap<K, V> linkedHashMap, int index) {
if (index < 0 || index >= linkedHashMap.size()) {
throw new IndexOutOfBoundsException();
}
Iterator<Entry<K, V>> iterator = linkedHashMap.entrySet().iterator();
for (int i = 0; i < index; i++) {
iterator.next();
}
return iterator.next().getValue();
}

Related

How to delete entry in Java TreeMap?

I am making a method, which takes a provided TreeMap, removes entries where the key is a multiple of keyFilter and the value contains the valueFilter character, and then returns the resulting TreeMap.
This is what I have so far:
public static TreeMap<Integer, String> filterTreeMap(
TreeMap<Integer, String> map, int keyFilter, char valueFilter) {
for (Map.Entry<Integer, String> entry : map.entrySet()) {
int mapKey = entry.getKey();
String mapValue = entry.getValue();
if (mapKey%keyFilter == 0 && mapValue.indexOf(valueFilter) != -1) {
map.remove(mapKey);
}
}
return map;
}
However, under the if condition where I want to delete the entries, I don't know how to delete entries in tree map. As far as I know, there is no existing method that I can use?
Use an Iterator. As the Iterator.remove() Javadoc notes
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
Something like
public static TreeMap<Integer, String> filterTreeMap(TreeMap<Integer, String> map,
int keyFilter, char valueFilter) {
Iterator<Map.Entry<Integer, String>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<Integer, String> entry = iter.next();
int mapKey = entry.getKey();
String mapValue = entry.getValue();
if (mapKey % keyFilter == 0 && mapValue.indexOf(valueFilter) != -1) {
iter.remove();
}
}
return map;
}
It is possible to apply method removeIf to the entry set.
default boolean removeIf(Predicate<? super E> filter)
Removes all of the elements of this collection that satisfy the given predicate. Errors or runtime exceptions thrown during iteration or by the predicate are relayed to the caller.
Implementation Requirements:
The default implementation traverses all elements of the collection using its iterator(). Each matching element is removed using Iterator.remove(). If the collection's iterator does not support removal then an UnsupportedOperationException will be thrown on the first matching element.
Then the method filterTreeMap may have void return type because the input map is modified and this change will be "visible" outside this method.
public static void filterTreeMap(
TreeMap<Integer, String> map, int keyFilter, char valueFilter) {
map.entrySet().removeIf(e ->
e.getKey() % keyFilter == 0
&& e.getValue().indexOf(valueFilter) != -1
);
}
Keys on the map are unique. So, find that keys, and then remove them form the map.
public static TreeMap<Integer, String> filterTreeMap(TreeMap<Integer, String> map,
int keyFilter, char valueFilter) {
Set<Integer> keysToRemove = map.entrySet().stream()
.filter(kv -> kv.getKey() % keyFilter == 0 && kv.getValue().indexOf(valueFilter) != -1) // can be Predicate parameter
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
keysToRemove.forEach(map::remove);
return map; // keep in mind, map is modified here. You might want to return a new map instead
}
Iterate over a copy and you can add/remove just fine:
for (Map.Entry<Integer, String> entry : new LinkedHashMap<Integer,String> (map).entrySet()) {
int mapKey = entry.getKey();
String mapValue = entry.getValue();
if (mapKey%keyFilter == 0 && mapValue.indexOf(valueFilter) != -1) {
map.remove(mapKey);
}
}
It's not even any more lines of code, because the copy is made in-line via the copy constructor. LinkedHashMap was chosen to preserve iteration order (if that matters).

What is the difference between iterating map in the below ways?

I have a array of String which has few words and I'm trying to find the most frequent (number of occurrences) words of k from the given array. I also have a constraint that consider the most frequent words are of frequency 2 then I need to consider the one which comes first in alphabetical order then the next ones.
I created a TreeMap to hold the words vs it's frequency count. Now the keys (ie' words) in the map would be sorted alphabetically. Now I was trying to sort the map based on it's values with the following snippet.
public static <K, V extends Comparable<V>> Map<K, V>
sortByValues(final Map<K, V> map) {
Comparator<K> valueComparator =
new Comparator<K>() {
public int compare(K k1, K k2) {
int compare =
map.get(k2).compareTo(map.get(k1));
if (compare == 0)
return 1;
else
return compare;
}
};
Map<K, V> sortedByValues =
new TreeMap<K, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}
Now I'm iterating the map in the following ways,
Method1
Map sortedMap = sortByValues(map);
ArrayList<String> result = new ArrayList<String>();
for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {
if (k-- <= 0) {
return result;
}
result.add(entry.getKey());
}
Method2
Map sortedMap = sortByValues(map);
ArrayList<String> result = new ArrayList<String>();
// Get a set of the entries on the sorted map
Set set = sortedMap.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
if (k-- <= 0) {
return result;
}
Map.Entry me = (Map.Entry)i.next();
result.add((String) me.getKey());
}
Consider the following content in TreeMap initially,
// Put elements to the map
treemap.put("love", 2);
treemap.put("i", 2);
treemap.put("coding", 1);
Method1 returns ["coding","i"] as output whereas Method2 way of iterating gives me ["i","love"].
Doubts
I'm confused with the two ways of iterating the map?
If I sort the TreeMap which is already sorted based on keys, if i sort again based by values will the sorting by keys be retained for equal value elements?

What is the main difference between LinkedList, HashSet and HashMap?

Well, you don't mind I will write my "test" project;
First of all I had created class that implements AbstractMap.
public class TestClass <K, V> extends AbstractMap <K, V>
TestClass has the private LinkedList that take as a parameter (It is another class that implements Map.Entry:
private int size = 1000;
private LinkedList <InfoClass <K, V>> [] array = new LinkedList [size];
After, I had created the method that checks and replaces duplicates:
public V put (K key, V value){ // Void doesn't work, therefore we need to return any value;
V temp = null;
boolean found = false;
int index = Math.abs(key.hashCode()) % size;
if (array[index] == null)
array[index] = new LinkedList <InfoClass <K, V>> (); // If the specified member of array is null, create new member;
LinkedList <InfoClass <K, V>> list = array[index];
InfoClass <K, V> info = new InfoClass <K, V> (key, value);
ListIterator <InfoClass <K, V>> it = list.listIterator();
while (it.hasNext()){
InfoClass<K, V> temp2 = it.next(); // Create a temp instance;
if (temp2.getKey().equals(key)){ // If there is a duplicate of value, just replace by new one;
found = true;
temp = temp2.getValue();
it.set(info);
break;
}
}
if (!found) // if there is not a duplicate, add new one;
array[index].add(info);
return temp;
}
Next method returns a value, otherwise this returns null if a member of array doesn't exist:
public V get (Object key){ // The parameter K doesn't work;
int index = Math.abs(key.hashCode()) % size;
if (array[index] == null)
return null;
else
for (InfoClass <K, V> info : array[index])
if (info.getKey().equals(key))
return info.getValue();
return null;
}
This method forms a set of AbstractMap:
public Set<java.util.Map.Entry<K, V>> entrySet() {
Set <Map.Entry<K, V>> sets = new HashSet <Map.Entry<K, V>> ();
for (LinkedList <InfoClass<K, V>> temp1 : array){
if (temp1 == null)
continue;
else{
for (InfoClass<K,V> temp2 : temp1)
sets.add(temp2);
}
}
return sets;
}
Ok, create new object in main method:
public static void main (String [] args){
TestClass <Integer, String> TC = new TestClass <Integer, String> ();
TC.putAll(CollectionDataMap.newCollection(new Group.Ints(), new Group.Name(), 10));
System.out.println(TC);
System.out.println(TC.get(1));
TC.put(1, "Hello this world");
System.out.println(TC);
}
Hope I explained correctly. I have a question, what is difference between LinkedList and LinkedHashMap (HashMap) if they work the same way?
Thank you very much!
LinkedList can contain the same element multiple times if the same element is added multiple times.
HashSet can only contain the same object once even if you add it multiple times, but it does not retain insertion order in the set.
LinkedHashSet can only contain the same object once even if you add it multiple times, but it also retains insertion order.
HashMap maps a value to a key, and the keys are stored in a set (so it can be in the set only once). HashMap doesn't preserve insertion order for the key set, while LinkedHashMap does retain insertion order for the keys.

The HashMap class in Java 8 appears to return the keyset in a different order than Java 7. Why? [duplicate]

I understand that the Set returned from a Map's keySet() method does not guarantee any particular order.
My question is, does it guarantee the same order over multiple iterations. For example
Map<K,V> map = getMap();
for( K k : map.keySet() )
{
}
...
for( K k : map.keySet() )
{
}
In the above code, assuming that the map is not modified, will the iteration over the keySets be in the same order. Using Sun's jdk15 it does iterate in the same order, but before I depend on this behavior, I'd like to know if all JDKs will do the same.
EDIT
I see from the answers that I cannot depend on it. Too bad. I was hoping to get away with not having to build some new Collection to guarantee my ordering. My code needed to iterate through, do some logic, and then iterate through again with the same ordering. I'll just create a new ArrayList from the keySet which will guarantee order.
You can use a LinkedHashMap if you want a HashMap whose iteration order does not change.
Moreover you should always use it if you iterate through the collection. Iterating over HashMap's entrySet or keySet is much slower than over LinkedHashMap's.
If it is not stated to be guaranteed in the API documentation, then you shouldn't depend on it. The behavior might even change from one release of the JDK to the next, even from the same vendor's JDK.
You could easily get the set and then just sort it yourself, right?
Map is only an interface (rather than a class), which means that the underlying class that implements it (and there are many) could behave differently, and the contract for keySet() in the API does not indicate that consistent iteration is required.
If you are looking at a specific class that implements Map (HashMap, LinkedHashMap, TreeMap, etc) then you could see how it implements the keySet() function to determine what the behaviour would be by checking out the source, you'd have to really take a close look at the algorithm to see if the property you are looking for is preserved (that is, consistent iteration order when the map has not had any insertions/removals between iterations). The source for HashMap, for example, is here (open JDK 6): http://www.docjar.com/html/api/java/util/HashMap.java.html
It could vary widely from one JDK to the next, so i definitely wouldn't rely on it.
That being said, if consistent iteration order is something you really need, you might want to try a LinkedHashMap.
The API for Map does not guarantee any ordering whatsoever, even between multiple invocations of the method on the same object.
In practice I would be very surprised if the iteration order changed for multiple subsequent invocations (assuming the map itself did not change in between) - but you should not (and according to the API cannot) rely on this.
EDIT - if you want to rely on the iteration order being consistent, then you want a SortedMap which provides exactly these guarantees.
Just for fun, I decided to write some code that you can use to guarantee a random order each time. This is useful so that you can catch cases where you are depending on the order but you should not be. If you want to depend on the order, than as others have said, you should use a SortedMap. If you just use a Map and happen to rely on the order then using the following RandomIterator will catch that. I'd only use it in testing code since it makes use of more memory then not doing it would.
You could also wrap the Map (or the Set) to have them return the RandomeIterator which would then let you use the for-each loop.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Main
{
private Main()
{
}
public static void main(final String[] args)
{
final Map<String, String> items;
items = new HashMap<String, String>();
items.put("A", "1");
items.put("B", "2");
items.put("C", "3");
items.put("D", "4");
items.put("E", "5");
items.put("F", "6");
items.put("G", "7");
display(items.keySet().iterator());
System.out.println("---");
display(items.keySet().iterator());
System.out.println("---");
display(new RandomIterator<String>(items.keySet().iterator()));
System.out.println("---");
display(new RandomIterator<String>(items.keySet().iterator()));
System.out.println("---");
}
private static <T> void display(final Iterator<T> iterator)
{
while(iterator.hasNext())
{
final T item;
item = iterator.next();
System.out.println(item);
}
}
}
class RandomIterator<T>
implements Iterator<T>
{
private final Iterator<T> iterator;
public RandomIterator(final Iterator<T> i)
{
final List<T> items;
items = new ArrayList<T>();
while(i.hasNext())
{
final T item;
item = i.next();
items.add(item);
}
Collections.shuffle(items);
iterator = items.iterator();
}
public boolean hasNext()
{
return (iterator.hasNext());
}
public T next()
{
return (iterator.next());
}
public void remove()
{
iterator.remove();
}
}
I agree with LinkedHashMap thing. Just putting my findings and experience while I was facing the problem when I was trying to sort HashMap by keys.
My code to create HashMap:
HashMap<Integer, String> map;
#Before
public void initData() {
map = new HashMap<>();
map.put(55, "John");
map.put(22, "Apple");
map.put(66, "Earl");
map.put(77, "Pearl");
map.put(12, "George");
map.put(6, "Rocky");
}
I have a function showMap which prints entries of map:
public void showMap (Map<Integer, String> map1) {
for (Map.Entry<Integer, String> entry: map1.entrySet()) {
System.out.println("[Key: "+entry.getKey()+ " , "+"Value: "+entry.getValue() +"] ");
}
}
Now when I print the map before sorting, it prints following sequence:
Map before sorting :
[Key: 66 , Value: Earl]
[Key: 22 , Value: Apple]
[Key: 6 , Value: Rocky]
[Key: 55 , Value: John]
[Key: 12 , Value: George]
[Key: 77 , Value: Pearl]
Which is basically different than the order in which map keys were put.
Now When I sort it with map keys:
List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
Collections.sort(entries, new Comparator<Entry<Integer, String>>() {
#Override
public int compare(Entry<Integer, String> o1, Entry<Integer, String> o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
for (Map.Entry<Integer, String> entry : entries) {
System.out.println("Putting key:"+entry.getKey());
sortedMap.put(entry.getKey(), entry.getValue());
}
System.out.println("Map after sorting:");
showMap(sortedMap);
the out put is:
Sorting by keys :
Putting key:6
Putting key:12
Putting key:22
Putting key:55
Putting key:66
Putting key:77
Map after sorting:
[Key: 66 , Value: Earl]
[Key: 6 , Value: Rocky]
[Key: 22 , Value: Apple]
[Key: 55 , Value: John]
[Key: 12 , Value: George]
[Key: 77 , Value: Pearl]
You can see the difference in order of keys. Sorted order of keys is fine but that of keys of copied map is again in the same order of the earlier map. I dont know if this is valid to say, but for two hashmap with same keys, order of keys is same. This implies to the statement that order of keys is not guaranteed but can be same for two maps with same keys because of inherent nature of key insertion algorithm if HashMap implementation of this JVM version.
Now when I use LinkedHashMap to copy sorted Entries to HashMap, I get desired result (which was natural, but that is not the point. Point is regarding order of keys of HashMap)
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
for (Map.Entry<Integer, String> entry : entries) {
System.out.println("Putting key:"+entry.getKey());
sortedMap.put(entry.getKey(), entry.getValue());
}
System.out.println("Map after sorting:");
showMap(sortedMap);
Output:
Sorting by keys :
Putting key:6
Putting key:12
Putting key:22
Putting key:55
Putting key:66
Putting key:77
Map after sorting:
[Key: 6 , Value: Rocky]
[Key: 12 , Value: George]
[Key: 22 , Value: Apple]
[Key: 55 , Value: John]
[Key: 66 , Value: Earl]
[Key: 77 , Value: Pearl]
Hashmap does not guarantee that the order of the map will remain constant over time.
It doesn't have to be. A map's keySet function returns a Set and the set's iterator method says this in its documentation:
"Returns an iterator over the elements in this set. The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee)."
So, unless you are using one of those classes with a guarantee, there is none.
Map is an interface and it does not define in the documentation that order should be the same. That means that you can't rely on the order. But if you control Map implementation returned by the getMap(), then you can use LinkedHashMap or TreeMap and get the same order of keys/values all the time you iterate through them.
tl;dr Yes.
I believe the iteration order for .keySet() and .values() is consistent (Java
8).
Proof 1: We load a HashMap with random keys and random values. We iterate on this HashMap using .keySet() and load the keys and it's corresponding values to a LinkedHashMap (it will preserve the order of the keys and values inserted). Then we compare the .keySet() of both the Maps and .values() of both the Maps. It always comes out to be the same, never fails.
public class Sample3 {
static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static SecureRandom rnd = new SecureRandom();
// from here: https://stackoverflow.com/a/157202/8430155
static String randomString(int len){
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
sb.append(AB.charAt(rnd.nextInt(AB.length())));
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
for (int j = 0; j < 10; j++) {
Map<String, String> map = new HashMap<>();
Map<String, String> linkedMap = new LinkedHashMap<>();
for (int i = 0; i < 1000; i++) {
String key = randomString(8);
String value = randomString(8);
map.put(key, value);
}
for (String k : map.keySet()) {
linkedMap.put(k, map.get(k));
}
if (!(map.keySet().toString().equals(linkedMap.keySet().toString()) &&
map.values().toString().equals(linkedMap.values().toString()))) {
// never fails
System.out.println("Failed");
break;
}
}
}
}
Proof 2: From here, the table is an array of Node<K,V> class. We know that iterating an array will give the same result every time.
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
The class responsible for .values():
final class Values extends AbstractCollection<V> {
// more code here
public final void forEach(Consumer<? super V> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
The class responsible for .keySet():
final class KeySet extends AbstractSet<K> {
// more code here
public final void forEach(Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
Carefully look at both the inner classes. They are pretty much the same except:
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.key); <- from KeySet class
// action.accept(e.value); <- the only change from Values class
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
They iterate on the same array table to support .keySet() in KeySet class and .values() in Values class.
Proof 3: this answer also explicitly states - So, yes, keySet(), values(), and entrySet() return values in the order the internal linked list uses.
Therefore, the .keySet() and .values() are consistent.
Logically, if the contract says "no particular order is guaranteed", and since "the order it came out one time" is a particular order, then the answer is no, you can't depend on it coming out the same way twice.
You also can store the Set instance returned by the keySet() method and can use this instance whenever you need the same order.

Sorting HashMap<?,?> by key

hello
I need to implement a method that receives a HashMap and sorts (mergeSort) it's values by key (without using TreeMap, SortedMap or Collections.Sort or use any sort solutions from JAVA Packages).
my problem is dealing with the wildcard Types...
this is my implementation (that returns compilation errors because of wildcards use)
public HashMap<?, ?> mergeSort(HashMap<?, ?> map) {
if (map.size() < 1) {
return map;
}
// rounds downwards
int middle = map.size() / 2;
int location = 0;
HashMap<?,?> mapLeft = new HashMap<?, ?>();
HashMap<?,?> mapRight = new HashMap<?, ?>();
// splitting map
for (Iterator<?> keyIter = map.keySet().iterator(); keyIter.hasNext();) {
if (location < middle) {
mapLeft.put(keyIter, map.get(keyIter));
} else {
mapRight.put(keyIter, map.get(keyIter));
}
location++;
}
// recursive call
mapLeft = mergeSort(mapLeft);
mapRight = mergeSort(mapRight);
return merge(mapLeft, mapRight);
}
public HashMap<?, ?> merge(HashMap<?, ?> mapLeft, HashMap<?, ?> mapRight) {
HashMap<?, ?> result = new HashMap<?, ?>();
Iterator<?> keyLeftIter = mapLeft.keySet().iterator();
Iterator<?> keyRightIter = mapRight.keySet().iterator();
String keyLeft;
String keyRight;
while (keyLeftIter.hasNext()) {
keyLeft = keyLeftIter.next();
while (keyRightIter.hasNext()) {
keyRight = keyRightIter.next();
if (keyLeft.compareTo(keyRight) < 0) {
result.put(keyLeft, mapLeft.get(keyLeft));
keyLeft = keyLeftIter.next();
} else {
result.put(keyRight, mapRight.get(keyRight));
keyRight = keyRightIter.next();
}
}
}
return result;
}
I appreciate your help!
If all you have to do is meet a method contract, you can do this.
public HashMap<?, ?> mergeSort(HashMap<?, ?> map) {
return new LinkedHashMap(new TreeMap(map));
}
This will sort the keys and return a subclass of HashMap. The design of this method is broken, but sometimes you can't change things.
If you are sorting a map, you should be using a SortedMap like TreeMap. hashmap doesn't retain an order so using it for a merge sort is not possible. Using a merge sort for a TreeMap is redundant.
You cannot assume that ? is a Comparable. You can write something like.
public static <K extends Comparable<K>, V> SortedMap<K,V> sort(Map<K,V> map) {
return new TreeMap<K, V>(map);
}
As you can see this is shorter and simpler than your approach. Is this homework? Do you reall need to use a merge sort?
The problem you have is that you cannot return a HashMap as it doesn't keep the order, adn you cannot return a TreeMap because it will sort the keys for you making anything else you redundant. For this task you can only return a LinkedHashMap as it does retain order, without doing the sorting for you.
here is an example using LinkedHashMap. Note it doesn't create copies of Maps as it goes, it creates a single array and merge sorts portions of it until its completely sorted.
Note: I use TreeMap as a SortedMap to show its sorted correctly. ;)
public static void main(String... args) throws IOException {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0;i<100;i++)
map.put((int)(Math.random()*1000), i);
System.out.println("Unsorted "+map);
System.out.println("Sorted "+sort(map));
final String sortedToString = sort(map).toString();
final String treeMapToString = new TreeMap<Integer, Integer>(map).toString();
if (!sortedToString.equals(treeMapToString))
System.out.println(sortedToString+" != \n"+treeMapToString);
}
public static <K extends Comparable<K>, V> Map<K, V> sort(Map<K, V> map) {
return mergeSort(map);
}
// a very bad design idea, but needed for compatibility.
public static <K extends Comparable<K>, V> HashMap<K, V> mergeSort(Map<K, V> map) {
Map.Entry<K, V>[] entries = map.entrySet().toArray(new Map.Entry[map.size()]);
mergeSort0(entries, 0, entries.length);
HashMap<K, V> ret = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : entries)
ret.put(entry.getKey(), entry.getValue());
return ret;
}
private static <K extends Comparable<K>, V> void mergeSort0(Map.Entry<K, V>[] entries, int start, int end) {
int len = end - start;
if (len < 2) return;
int mid = (end + start) >>> 1;
mergeSort0(entries, start, mid);
mergeSort0(entries, mid, end);
// merge [start, mid) and [mid, end) to [start, end)
for(int p = start, l=start, r=mid; p < end && l < r && r < end; p++) {
int cmp = entries[l].getKey().compareTo(entries[r].getKey());
if (cmp <= 0) {
l++;
// the entry is in the right place already
} else if (p != r) {
// we need to insert the entry from the right
Map.Entry<K,V> e= entries[r];
// shift up.
System.arraycopy(entries, p, entries, p+1, r - p);
l++;
// move down.
entries[p] = e;
r++;
}
}
}
prints
Unsorted {687=13, 551=0, 2=15, 984=3, 608=6, 714=16, 744=1, 272=5, 854=9, 96=2, 918=18, 829=8, 109=14, 346=7, 522=4, 626=19, 495=12, 695=17, 247=11, 725=10}
Sorted {2=15, 96=2, 109=14, 247=11, 272=5, 346=7, 495=12, 522=4, 551=0, 608=6, 626=19, 687=13, 695=17, 714=16, 725=10, 744=1, 829=8, 854=9, 918=18, 984=3}
Like other commenters I would suggest reading up on the subject of generics in Java. What you did in merge is using wildcards on the result HashMap
HashMap<?, ?> result = new HashMap<?, ?>();
When you put wildcards on it, you are basically saying "I will only be reading from this". Later on you trying to push something in
result.put(keyLeft, mapLeft.get(keyLeft));
The compiler will say "Hey, you just told me you would only read and now you want to put something in... FAIL
Then it generates your compile time errors.
Solution
Don't put wildcards on collections you will modify.
Why are you always using ?. Give the kids a name like Key or Value.
Edit: You should work through this tutorial fist: Lesson: Generics
Here is a method that sorts a Map by its keys. It makes use of the Collections.sort(List, Comparator) method.
static Map sortByKey(Map map) {
List list = new LinkedList(map.entrySet());
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getKey())
.compareTo(((Map.Entry) (o2)).getKey());
}
});
Map result = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
result.put(entry.getKey(), entry.getValue());
}
return result;
}

Categories