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

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


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

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


2. 🧰 Collection接口能做什么?

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

🔹 基本容器操作

  • 添加元素(add()
  • 删除元素(remove()
  • 检查某个元素是否存在(contains()
  • 获取容器中元素的数量(size()
  • 检查集合是否为空(isEmpty()
  • 清空集合(clear()

🔹 集合操作

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

  • 包含检查containsAll()):判断一个集合是否包含另一个集合的所有元素
  • 并集addAll()):把另一个集合的元素加入当前集合
  • 交集retainAll()):只保留当前集合和指定集合共有的元素
  • 差集removeAll()):移除当前集合中出现在指定集合里的元素

🔹 访问元素的方式

  • 使用 Iterator 遍历元素(iterator()
  • 通过 Stream 流式处理元素(stream(),可以并行parallelStream()

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

🎯 小总结:

  • Collection接口是各种集合容器的统一标准。
  • ListSet等更具体的集合,继承了这些基本操作,但各自有额外特性

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

虽然 ListSet 都是 Collection,但是:

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

📌 举个例子:

  • 想存放一组可以重复的、顺序重要的东西?➡️用 List
  • 想存放一组无重复的、只关心存在与否的东西?➡️用 Set

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(),可以更灵活地处理集合里的元素!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容