Set 是无序、不可重复的集合;Map 是键值对(key-value)。
1. Set 集合
Set 不允许重复元素。常用实现是 HashSet(无序)和 TreeSet(有序)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import java.util.HashSet; import java.util.Set;
public class SetDemo { public static void main(String[] args) { Set<String> set = new HashSet<>();
set.add("Java"); set.add("Python"); set.add("Java"); set.add("C++");
System.out.println(set); System.out.println(set.size());
System.out.println(set.contains("Java"));
for (String s : set) { System.out.println(s); } } }
|
去重示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;
public class DedupDemo { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(2); list.add(3); list.add(3); list.add(3);
Set<Integer> set = new HashSet<>(list); System.out.println(set); } }
|
2. Map 集合
Map 存的是「键 → 值」的映射,键不能重复。最常用的是 HashMap。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import java.util.HashMap; import java.util.Map;
public class MapDemo { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>();
map.put("Java", 100); map.put("Python", 90); map.put("C++", 80); System.out.println(map);
System.out.println(map.get("Java"));
System.out.println(map.containsKey("Java"));
System.out.println(map.size());
map.put("Java", 120); System.out.println(map.get("Java"));
map.remove("C++"); System.out.println(map); } }
|
3. 遍历 Map
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import java.util.HashMap; import java.util.Map;
public class MapTraverseDemo { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("Java", 100); map.put("Python", 90); map.put("C++", 80);
for (String key : map.keySet()) { System.out.println(key + " -> " + map.get(key)); }
for (Integer value : map.values()) { System.out.println(value); }
for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } } }
|
4. 统计词频示例(综合练习)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import java.util.HashMap; import java.util.Map;
public class WordCountDemo { public static void main(String[] args) { String text = "apple banana apple orange banana apple";
Map<String, Integer> count = new HashMap<>(); for (String word : text.split(" ")) { count.put(word, count.getOrDefault(word, 0) + 1); }
System.out.println(count); } }
|
5. 常见实现对比
| 集合 |
实现 |
特点 |
| Set |
HashSet |
无序、去重 |
| Set |
TreeSet |
有序(自然排序) |
| Map |
HashMap |
无序,键不能重复 |
| Map |
TreeMap |
按键排序 |
小结
Set 无序去重,List 有序可重复
Map 是键值对,put 存、get 取、键不能重复
- 遍历 Map 用
entrySet()