Java putting Hashmap into Treemap
Asked Answered
F

3

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);
Fatherinlaw answered 22/10, 2013 at 8:33 Comment(4)
Collections.sort(hMap) ? ,Collections.sort(hMap,WITH_MY_OWN_COMPARATOR) ?Mooned
Why not just put it directly into a TreeMap ? Why the extra step?Herv
hrm...i still prefer to sort it with treemap but as of my code, the treemap is emptyFatherinlaw
@suresh atta : Collections.sort(hMap) won't work, sort() work with List onlySemolina
C
36
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
treeMap.putAll(hashMap);

Should work anyway.

Chickenhearted answered 22/10, 2013 at 8:37 Comment(8)
Are you just kidding ??? Passing constructor also calls putAll() :). Checkout the source code link, I addedMooned
@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.Mooned
It's correct, but the usage of the constructor is more elegant.Chickenhearted
@user2822351The question is... is it any different from what you have posted in ur question above !?Brinker
@ Akkusativobjekt, i am using constructor but it doesnt work. the treemap is empty when i try to print outFatherinlaw
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.Mooned
@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 hashmapFatherinlaw
@user2822351 Ooops.Happens some time. Good catch. I'l be happy If you delete this post :)Mooned
F
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.

Facilitate answered 7/6, 2016 at 9:55 Comment(0)
C
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

Cuprous answered 6/9, 2016 at 7:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.