Java 集合框架

List / Set / Map 创建、遍历、排序、去重

创建

List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
Map<String, Integer> map = new HashMap<>();
// 不可变集合(Java 9+)
List<String> fixed = List.of("a", "b", "c");
Map<String, Integer> m2 = Map.of("a", 1, "b", 2);

遍历

for (String s : list) { }
map.forEach((k, v) -> System.out.println(k + "=" + v));
// 遍历时删除要用迭代器,否则 ConcurrentModificationException
Iterator<String> it = list.iterator();
while (it.hasNext()) { if (...) it.remove(); }

排序与去重

list.sort(Comparator.comparing(String::length).reversed());
list.sort(Comparator.comparing(User::getAge).thenComparing(User::getName));
List<String> uniq = new ArrayList<>(new LinkedHashSet<>(list));  // 去重保序

判空与线程安全

if (list != null && !list.isEmpty()) { }
Map<String, String> safe = new ConcurrentHashMap<>();
List<String> sync = Collections.synchronizedList(new ArrayList<>());

选型

场景 用
随机访问多 ArrayList
增删多 LinkedList
去重 HashSet(TreeSet 可排序)
键值 HashMap(需线程安全用 ConcurrentHashMap)

← 返回速查表