Reputation: 2455
I have a HashMap which contains String as key , and an Object as value In order to sort my HashMap I create a TreeMap , iterate over the HashMap and put each entry of the HashMap into a TreeMap where key is bandwidth and value the instance of signal.Here is my code
public void createSortedSet(HashMap<String, Signal> map, long totalSize) {
TreeMap<Float, Signal> sortedMap = new TreeMap<Float, Signal>();
JOptionPane.showMessageDialog(null, map.size());
try {
final Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String messageName = iterator.next();
Signal signal = map.get(messageName);
signal.setBandwidth((signal.getSize() / (float) totalSize) * 100);
sortedMap.put(signal.getBandwidth(), signal);
}
JOptionPane.showMessageDialog(null, sortedMap.size());
} catch (Exception e) {
e.printStackTrace();
}
}
The problem here is the size of map is 8318 while after the while loop when I check the size of TreeMap it gives 455?? Does it mean that not all the instances of the signal are stored in TreeMap
Any Help ?
Upvotes: 0
Views: 5681
Reputation: 4628
Different signals contain equals bandwidth sortedMap.put(signal.getBandwidth(), signal);
.
Upvotes: 0
Reputation: 719310
I expect that problem is that you have entries in the original map whose "size" (as returned by getSize()
) is the same. Since a Map cannot hold multiple values for the same key, entries from the original which have the same "size" are being eliminated.
Upvotes: 0
Reputation: 9231
Note that you're using a different key in the TreeMap
than you do in the HashMap
. Being a Map
, keys have to be unique. The put
method will replace any previous value with the same key. It is likely that your calculation of the new key yields duplicates and causes the size of the new map to be lower than the old map.
Upvotes: 0