简体   繁体   English

将HashMap转换为排序的TreeMap

[英]Converting a HashMap to a Sorted TreeMap

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 我有一个HashMap,其中包含String作为键,并包含一个Object作为值。为了对我的HashMap进行排序,我创建了一个TreeMap,遍历HashMap并将HashMap的每个条目放入TreeMap中,键为带宽,并指定信号实例这是我的代码

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?? 这里的问题是映射的大小是8318,而在while循环之后,当我检查TreeMap的大小时,它给出了455? Does it mean that not all the instances of the signal are stored in TreeMap 这是否意味着并非信号的所有实例都存储在TreeMap中

Any Help ? 有帮助吗?

Note that you're using a different key in the TreeMap than you do in the HashMap . 请注意,在TreeMap使用的键与在HashMap使用的键不同。 Being a Map , keys have to be unique. 作为Map ,键必须是唯一的。 The put method will replace any previous value with the same key. put方法将用相同的键替换任何先前的值。 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. 您对新密钥的计算可能会产生重复,并使新地图的尺寸​​小于旧地图。

I expect that problem is that you have entries in the original map whose "size" (as returned by getSize() ) is the same. 我希望这个问题是您在原始地图中具有“大小”(由getSize()返回)相同的条目。 Since a Map cannot hold multiple values for the same key, entries from the original which have the same "size" are being eliminated. 由于Map不能为同一键包含多个值,因此将消除具有相同“大小”的原始条目。

Different signals contain equals bandwidth sortedMap.put(signal.getBandwidth(), signal); 不同的信号包含相等的带宽sortedMap.put(signal.getBandwidth(), signal); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM