简体   繁体   English

Java HashMap 移位值

[英]Java HashMap Shift Value

I have hash map like this below.And i want to shift values up when upper values are null.我有 hash map 如下所示。当上限值为 null 时,我想将值上移。

HashMap 
Key1 Val1
Key2 
Key3 
Key4 Val4
Key5 
Key6 Val6

Become like this变成这样

HashMap 
Key1 Val1
Key2 Val4
Key3 Val6
Key4 
Key5 
Key6 

And then delete null value key like this.然后像这样删除 null 值键。

HashMap 
Key1 Val1
Key2 Val4
Key3 Val6

You can't do this meaningfully with a HashMap because it doesn't have a defined ordering, so there is no "second key" - Key2 - to move Val4 up to.您无法使用HashMap有意义地执行此操作,因为它没有定义的顺序,因此没有“第二个键” - Key2 - 可以将Val4向上移动。

But you can do it if you have an ordered Map , such as a TreeMap (this code works generally on any mutable Map ; but it only gives predictable results on a map with defined iteration order):但是,如果您有一个有序的Map ,例如TreeMap ,则可以执行此操作(此代码通常适用于任何可变Map ;但它仅在具有定义的顺序迭代的 map 上给出可预测的结果):

Iterator<? extends Map.Entry<?, V>> entryIterator = map.entrySet().iterator();
// Find non-null values, set the next entry's value to that.
for (String val : map.values()) {
  if (val != null) {
    entryIterator.next().setValue(val);
  }
}

// Remove the rest of the entries, because we have no non-null
// values to assign to them.
while (entryIterator.hasNext()) {
  entryIterator.next();
  entryIterator.remove();
}

Ideone Demo Ideone 演示

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

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