224. Java 集合 - 使用 Collection 接口存

2025-10-29  本文已影响0人  Cache技术分享

224. Java 集合 - 使用 Collection 接口存储元素


1. 🚪 集合接口(Collection Interface)的入口

Java 的集合框架中,除了Map之外,其他所有接口都是在处理存储元素到容器中的问题。
ListSet这两个重要接口,共同继承了Collection接口,它们的基本行为都是由Collection统一建模的。


2. 🧰 Collection接口能做什么?

在不涉及过多技术细节的情况下,Collection接口提供了一组通用操作,包括:

🔹 基本容器操作

🔹 集合操作

因为集合本身是"元素的合集",所以也支持一些"集合论"相关的操作,比如:

🔹 访问元素的方式


3. 🌟 例子:Collection基本操作演示

import java.util.*;

public class CollectionExample {
    public static void main(String[] args) {
        Collection<String> fruits = new ArrayList<>();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        System.out.println("Fruits: " + fruits);
        System.out.println("Contains 'Banana'? " + fruits.contains("Banana"));
        System.out.println("Size: " + fruits.size());

        fruits.remove("Apple");
        System.out.println("After removing 'Apple': " + fruits);

        Collection<String> tropicalFruits = List.of("Banana", "Mango");
        System.out.println("Fruits contains all tropical fruits? " + fruits.containsAll(tropicalFruits));

        fruits.addAll(tropicalFruits);
        System.out.println("After adding tropical fruits: " + fruits);

        fruits.retainAll(List.of("Banana"));
        System.out.println("After retaining only 'Banana': " + fruits);

        fruits.clear();
        System.out.println("Is collection empty after clear()? " + fruits.isEmpty());
    }
}

运行输出:

Fruits: [Apple, Banana, Orange]
Contains 'Banana'? true
Size: 3
After removing 'Apple': [Banana, Orange]
Fruits contains all tropical fruits? false
After adding tropical fruits: [Banana, Orange, Banana, Mango]
After retaining only 'Banana': [Banana, Banana]
Is collection empty after clear()? true

🎯 小总结:


4. ❓ 那么,Collection、List 和 Set 到底有什么区别?

虽然 ListSet 都是 Collection,但是:

特性 Collection List Set
是否有序? 不一定 有序(按插入顺序或自定义排序) 无序(有些实现可以有顺序,如LinkedHashSet
是否允许重复? 不确定 允许重复元素 不允许重复元素
如何访问? 迭代或流 通过索引(get(index) 通过迭代

📌 举个例子:


5. 🌊 示例:使用Stream流式处理Collection

import java.util.*;

public class StreamExample {
    public static void main(String[] args) {
        Collection<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);

        numbers.stream()
               .filter(n -> n % 2 == 0)
               .forEach(System.out::println);  // 打印偶数
    }
}

输出:

2
4
6

🎯 这里用到了 stream(),可以更灵活地处理集合里的元素!

上一篇 下一篇

猜你喜欢

热点阅读