17

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);
4
  • 1
    Collections.sort(hMap) ? ,Collections.sort(hMap,WITH_MY_OWN_COMPARATOR) ? Commented Oct 22, 2013 at 8:35
  • 4
    Why not just put it directly into a TreeMap ? Why the extra step? Commented Oct 22, 2013 at 8:36
  • hrm...i still prefer to sort it with treemap but as of my code, the treemap is empty Commented Oct 22, 2013 at 8:36
  • @suresh atta : Collections.sort(hMap) won't work, sort() work with List only Commented Feb 12, 2018 at 7:17

3 Answers 3

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

Should work anyway.

Sign up to request clarification or add additional context in comments.

8 Comments

Are you just kidding ??? Passing constructor also calls putAll() :). Checkout the source code link, I added
@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.
It's correct, but the usage of the constructor is more elegant.
@user2822351The question is... is it any different from what you have posted in ur question above !?
@ Akkusativobjekt, i am using constructor but it doesnt work. the treemap is empty when i try to print out
|
8

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.