HashMap Key去重:Java示例代码
要去重HashMap的key,可以使用以下步骤:
- 创建一个新的HashMap,用于存储去重后的key。
- 遍历原始HashMap的所有key。
- 检查新的HashMap中是否已经存在该key。
- 如果新的HashMap中不存在该key,则将该key添加到新的HashMap中。
- 完成遍历后,新的HashMap中的key就是去重后的结果。
以下是一个示例代码:
import java.util.HashMap;
import java.util.Map;
public class HashMapKeyDeduplication {
public static void main(String[] args) {
HashMap<Integer, String> originalMap = new HashMap<>();
originalMap.put(1, 'A');
originalMap.put(2, 'B');
originalMap.put(3, 'C');
originalMap.put(1, 'D'); // 重复的key
HashMap<Integer, String> deduplicatedMap = new HashMap<>();
for (Integer key : originalMap.keySet()) {
if (!deduplicatedMap.containsKey(key)) {
deduplicatedMap.put(key, originalMap.get(key));
}
}
// 输出去重后的结果
for (Map.Entry<Integer, String> entry : deduplicatedMap.entrySet()) {
System.out.println('Key: ' + entry.getKey() + ', Value: ' + entry.getValue());
}
}
}
输出结果:
Key: 1, Value: A
Key: 2, Value: B
Key: 3, Value: C
在上面的示例中,原始的HashMap中有一个重复的key(1和'D')。通过遍历原始HashMap的key,将不重复的key添加到新的HashMap中,实现了去重。
原文地址: https://www.cveoy.top/t/topic/qkHO 著作权归作者所有。请勿转载和采集!