3 回答

TA貢獻1865條經驗 獲得超7個贊
另一種方法是使用mapKeys
擴展函數,它允許您重新定義映射條目的鍵:
fun main() {
val originalMap = mapOf(1 to "value1", 2 to "value2", 3 to "value3")
val updatedMap = originalMap
.mapKeys {
if (it.key > 1) {
it.key - 1
} else {
it.key
}
}
println(updatedMap) // prints: {1=value2, 2=value3}
}
請注意,這不會就地更新地圖,但會創建一個新地圖。另請注意:
如果任何兩個條目映射到相同的鍵,則后一個的值將覆蓋與前一個關聯的值。
這意味著如果兩個鍵發生沖突,通常您無法知道哪個會“獲勝”(除非您使用的是LinkedHashMap
,它保留了插入順序)。
更通用的方法是:
遞減所有鍵
過濾掉所有非正鍵
不過,這將需要 2 次完整迭代(除非您使用Sequences
,它是惰性求值的):
fun main() {
val originalMap = mapOf(1 to "value1", 2 to "value2", 3 to "value3")
val updatedMap = originalMap
.mapKeys {
it.key - 1
}.filter {
it.key > 0
}
println(updatedMap)
}

TA貢獻1872條經驗 獲得超4個贊
這里與 Java 7 兼容代碼相同(無流)
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "test1");
hashMap.put(2, "test2");
hashMap.put(3, "test3");
Map<Integer, String> yourNewHashMap = new HashMap<>();
for (final Map.Entry<Integer, String> entry : hashMap.entrySet()) {
if (entry.getKey() != 1) { // make sure index 1 is omitted
yourNewHashMap.put(entry.getKey() - 1, entry.getValue()); // decrease the index for each key/value pair and add it to the new map
}
}
流的舊答案:
由于新的 Map 對象對你來說沒問題,我會使用以下流:評論是內聯的
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "test1");
hashMap.put(2, "test2");
hashMap.put(3, "test3");
// use this
Map<Integer, String> yourNewHashMap = hashMap.entrySet().stream()
.filter(es -> es.getKey() != 1) // make sure index 1 is omitted
.map(es -> new AbstractMap.SimpleEntry<Integer, String>(es.getKey() - 1, es.getValue())) // decrease the index for each key/value pair
.collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); // create a new map

TA貢獻1841條經驗 獲得超3個贊
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
// Populate the HashMap
map.put(1, "Value1");
map.put(2, "Value2");
map.put(3, "Value3");
System.out.println("Original HashMap: "
+ map);
decreaseAllKeysByOne(map);
}
private static void decreaseAllKeysByOne(HashMap<Integer, String> map) {
// Add your condition (if key>1)
HashMap<Integer, String> newMap = new HashMap<>();
map.remove(1);
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
int i = 1;
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
newMap.put(i, entry.getValue());
i++;
}
System.out.println("Modified HashMap: "
+ newMap);
}
輸出 :
原始 HashMap:{1=Value1, 2=Value2, 3=Value3}
修改后的 HashMap:{1=Value2, 2=Value3}
添加回答
舉報