Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java putting Hashmap into Treemap

I am currently reading 2 million lines from a textfile as asked in the previous question Java Fastest way to read through text file with 2 million lines

Now I store these information into HashMap and I want to sort it via TreeMap because I want to use ceilingkey. Is the following method correct?

private HashMap<Integer, String> hMap = new HashMap();

private TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(hMap);
like image 458
BeyondProgrammer Avatar asked Oct 22 '13 08:10

BeyondProgrammer


People also ask

Why would anyone use TreeMap over HashMap?

TreeMap provides a performance of O(log(n)) for most operations like add(), remove() and contains() A Treemap can save memory (in comparison to HashMap) because it only uses the amount of memory needed to hold its items, unlike a HashMap which uses contiguous region of memory.

Is HashMap better than TreeMap?

HashMap is faster than TreeMap because it provides constant-time performance that is O(1) for the basic operations like get() and put(). TreeMap is slow in comparison to HashMap because it provides the performance of O(log(n)) for most operations like add(), remove() and contains().

Can we cast HashMap to LinkedHashMap?

Of course, you can create a LinkedHashMap from a HashMap , but it isn't guaranteed that the LinkedHashMap will have the same order that your original did.


1 Answers

HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
treeMap.putAll(hashMap);

Should work anyway.

like image 186
Akkusativobjekt Avatar answered Oct 13 '22 04:10

Akkusativobjekt