16

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);
Community
  • 1
  • 1
BeyondProgrammer
  • 893
  • 2
  • 15
  • 32

3 Answers3

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

Should work anyway.

Akkusativobjekt
  • 2,005
  • 1
  • 21
  • 26
  • 3
    Are you just kidding ??? [Passing constructor also calls](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/TreeMap.java#TreeMap.%3Cinit%3E%28java.util.Map%29) `putAll()` :). Checkout the source code link, I added – Suresh Atta Oct 22 '13 at 08:41
  • @user2822351 I'm not telling that this answer is wrong, What I'm telling is this answer is equals to what you are doing right now. – Suresh Atta Oct 22 '13 at 08:44
  • 2
    It's correct, but the usage of the constructor is more elegant. – Akkusativobjekt Oct 22 '13 at 08:45
  • @user2822351The question is... is it any different from what you have posted in ur question above !? – codeMan Oct 22 '13 at 08:45
  • @ Akkusativobjekt, i am using constructor but it doesnt work. the treemap is empty when i try to print out – BeyondProgrammer Oct 22 '13 at 08:46
  • Then that is the problem, Post your full code. A simple test would be print the original map and then print tree map and see for difference. – Suresh Atta Oct 22 '13 at 08:48
  • @sᴜʀᴇsʜ ᴀᴛᴛᴀ oh gosh i manage to solve it, because the hashmap is added at runtime, so i have to construct it after i have added to the hashmap – BeyondProgrammer Oct 22 '13 at 08:51
  • @user2822351 Ooops.Happens some time. Good catch. I'l be happy If you delete this post :) – Suresh Atta Oct 22 '13 at 08:53
6

This would work just fine:

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

But I wouldn't advise using HashMap to store the input. You end up with two Maps holding the same huge data. Either do it on the fly and add directly into TreeMap or use List to TreeMap conversion.

Also, for even more efficiency consider primitive collections.

Community
  • 1
  • 1
husayt
  • 14,553
  • 8
  • 53
  • 81
2
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
hashMap.remove(null);
treeMap.putAll(hashMap);

HashMap will allow null but TreeMap not so before adding into Treemap, remove null from keyset