以下是基于Java最新技术(JDK 11+)的集合框架实操内容,结合了Java 8+的新特性(如Stream API、Lambda表达式)和并发编程的最佳实践。
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class CollectionPractice {
// 一、List操作示例
public static void listOperations() {
// 1. ArrayList的现代初始化和操作
ArrayList<String> arrayList = new ArrayList<>(List.of("apple", "banana", "cherry"));
arrayList.add("date");
arrayList.removeIf(fruit -> fruit.startsWith("b")); // 使用Lambda过滤元素
// 使用Stream API处理列表
arrayList.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
// 2. LinkedList的双向操作
LinkedList<Integer> linkedList = new LinkedList<>();
linkedList.addFirst(100);
linkedList.addLast(200);
linkedList.push(50); // 等价于addFirst
// 使用迭代器安全删除元素
Iterator<Integer> iterator = linkedList.iterator();
while (iterator.hasNext()) {
if (iterator.next() == 100) {
iterator.remove();
}
}
}
// 二、Map操作示例
public static void mapOperations() {
// 1. HashMap的流式操作
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 1);
hashMap.put("banana", 2);
hashMap.put("cherry", 3);
// 计算所有值的总和
int sum = hashMap.values().stream()
.mapToInt(Integer::intValue)
.sum();
// 过滤键值对
Map<String, Integer> filteredMap = hashMap.entrySet().stream()
.filter(entry -> entry.getValue() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// 2. ConcurrentHashMap的原子操作
ConcurrentHashMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put("apple", 1);
// 原子性更新操作
concurrentMap.compute("apple", (k, v) -> v == null ? 1 : v + 1);
concurrentMap.putIfAbsent("banana", 2);
// 并行流处理
concurrentMap.entrySet().parallelStream()
.forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue()));
}
// 三、Set操作示例
public static void setOperations() {
// 1. HashSet的流式操作
HashSet<String> hashSet = new HashSet<>(Set.of("apple", "banana", "cherry"));
hashSet.add("date");
// 检查是否所有元素都满足条件
boolean allStartWithA = hashSet.stream()
.allMatch(fruit -> fruit.startsWith("a"));
// 2. TreeSet的有序操作
TreeSet<Integer> treeSet = new TreeSet<>(Comparator.reverseOrder());
treeSet.addAll(Set.of(3, 1, 4, 1, 5, 9, 2, 6, 5));
// 获取小于5的最大值
Integer floorValue = treeSet.floor(5);
// 3. CopyOnWriteArraySet的并发操作
CopyOnWriteArraySet<String> concurrentSet = new CopyOnWriteArraySet<>();
concurrentSet.add("apple");
// 安全地遍历集合(迭代器创建时的快照)
for (String element : concurrentSet) {
concurrentSet.add(element.toUpperCase());
}
}
// 四、Queue和Deque操作示例
public static void queueOperations() {
// 1. PriorityQueue的比较器使用
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
minHeap.addAll(List.of(5, 3, 7, 1));
maxHeap.addAll(List.of(5, 3, 7, 1));
System.out.println("Min heap peek: " + minHeap.peek()); // 输出1
System.out.println("Max heap peek: " + maxHeap.peek()); // 输出7
// 2. ArrayDeque的双端队列操作
ArrayDeque<String> deque = new ArrayDeque<>();
deque.offerFirst("head");
deque.offerLast("tail");
deque.pollFirst();
deque.pollLast();
}
// 五、集合转换和聚合操作
public static void advancedOperations() {
// 1. 集合间的转换
List<String> list = Arrays.asList("apple", "banana", "cherry");
Set<String> set = new LinkedHashSet<>(list);
Map<Integer, String> map = IntStream.range(0, list.size())
.boxed()
.collect(Collectors.toMap(
i -> i,
list::get,
(existing, replacement) -> existing,
LinkedHashMap::new
));
// 2. 复杂聚合操作
List<Person> persons = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 20),
new Person("Charlie", 30)
);
// 按条件分组
Map<String, List<Person>> ageGroup = persons.stream()
.collect(Collectors.groupingBy(p -> p.getAge() > 25 ? "Old" : "Young"));
// 计算平均年龄
double averageAge = persons.stream()
.mapToInt(Person::getAge)
.average()
.orElse(0);
}
// 示例类
static class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public static void main(String[] args) {
listOperations();
mapOperations();
setOperations();
queueOperations();
advancedOperations();
}
}
代码说明:
List操作:
- 使用Java 9的
List.of()
工厂方法初始化不可变列表 - 演示
removeIf()
方法和Lambda表达式的结合使用 - 展示Stream API的链式操作和方法引用
- 使用Java 9的
Map操作:
- 展示HashMap的流式处理和过滤操作
- 演示ConcurrentHashMap的原子性操作(
compute()
、putIfAbsent()
) - 使用并行流处理并发Map
Set操作:
- 演示TreeSet的比较器使用(降序排列)
- 使用CopyOnWriteArraySet进行线程安全的并发操作
- 展示集合的流式匹配操作(
allMatch()
)
Queue和Deque操作:
- 实现优先队列(最小堆和最大堆)
- 使用ArrayDeque作为双端队列进行首尾操作
高级操作:
- 集合间的相互转换(List→Set→Map)
- 使用Collectors进行复杂聚合操作(分组、平均值计算)
- 演示Java 8的IntStream和装箱操作
这些示例覆盖了Java集合框架的核心功能,并结合了Java 8+的新特性,展示了现代Java编程的最佳实践。
J
代码获取方式
https://pan.quark.cn/s/14fcf913bae6