在 Java 中,HashMap 和 HashSet 是最常用的哈希表实现类。下面我将展示几种常见的用法,包括使用 HashMap 进行频次统计、查找配对和双向映射,以及使用 HashSet 进行去重。
1. 使用 HashMap 进行频次统计
假设你有一个字符串,想统计其中每个字符的出现频率。
import java.util.HashMap;
public class FrequencyCount {
public static void main(String[] args) {
String str = "hello world";
HashMap<Character, Integer> freqMap = new HashMap<>();
for (char c : str.toCharArray()) {
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
}
System.out.println(freqMap);
}
}
这个代码会输出每个字符的出现次数,如:{ =1, d=1, e=1, h=1, l=3, o=2, r=1, w=1}。
2. 使用 HashMap 查找两个数的和等于目标值
给定一个数组和目标值,找出两个数的和为目标值。
import java.util.HashMap;
public class TwoSum {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
System.out.println("Pair found: (" + nums[i] + ", " + complement + ")");
return;
}
map.put(nums[i], i);
}
System.out.println("No pair found");
}
}
输出结果为:Pair found: (7, 2)。
3. 使用 HashSet 进行去重
假设你有一个数组,想要去除其中的重复元素。
import java.util.HashSet;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] nums = {1, 2, 2, 3, 4, 4, 5};
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
System.out.println(set);
}
}
输出结果为:[1, 2, 3, 4, 5],即去掉了重复的元素。
4. 使用 HashMap 实现双向映射
这个例子演示了如何使用 HashMap 来创建双向映射,即既可以从键查找值,也可以从值查找键。
import java.util.HashMap;
public class BiMap {
private HashMap<String, Integer> keyToValue = new HashMap<>();
private HashMap<Integer, String> valueToKey = new HashMap<>();
public void put(String key, Integer value) {
keyToValue.put(key, value);
valueToKey.put(value, key);
}
public Integer getValue(String key) {
return keyToValue.get(key);
}
public String getKey(Integer value) {
return valueToKey.get(value);
}
public static void main(String[] args) {
BiMap map = new BiMap();
map.put("apple", 1);
map.put("banana", 2);
System.out.println("Value for apple: " + map.getValue("apple"));
System.out.println("Key for value 2: " + map.getKey(2));
}
}
输出结果为:
Value for apple: 1
Key for value 2: banana
5. 使用 HashSet 检查数组中是否有重复元素
如果你想快速判断一个数组中是否存在重复元素,可以使用 HashSet。
import java.util.HashSet;
public class CheckDuplicates {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6, 2};
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
if (!set.add(num)) {
System.out.println("Duplicate found: " + num);
return;
}
}
System.out.println("No duplicates found");
}
}
输出结果为:Duplicate found: 2。
总结:
HashMap用于键值对的存储,可以高效地进行查找、插入、删除。HashSet用于去重,判断某个元素是否已经存在。 这些哈希表的实现能够使我们在常数时间内进行查找、更新和删除操作,大大提高了代码的效率。
浙公网安备 33010602011771号