Java Collections案例怎么操作集合

wen java案例 26

本文目录导读:

Java Collections案例怎么操作集合

  1. List集合操作案例
  2. Set集合操作案例
  3. Map集合操作案例
  4. 集合工具类操作
  5. 实战案例:学生管理系统
  6. 主要注意事项:

我来为你详细讲解Java集合框架的常用操作案例。

List集合操作案例

ArrayList基本操作

import java.util.*;
public class ListExample {
    public static void main(String[] args) {
        // 创建ArrayList
        List<String> list = new ArrayList<>();
        // 添加元素
        list.add("Java");
        list.add("Python");
        list.add("JavaScript");
        list.add(1, "C++");  // 在指定位置插入
        // 获取元素
        String first = list.get(0);
        System.out.println("第一个元素: " + first);
        // 修改元素
        list.set(2, "Ruby");
        // 删除元素
        list.remove("Python");  // 按对象删除
        list.remove(1);         // 按索引删除
        // 遍历操作
        System.out.println("遍历列表:");
        for (String lang : list) {
            System.out.println(lang);
        }
        // 其他常用操作
        System.out.println("列表大小: " + list.size());
        System.out.println("是否为空: " + list.isEmpty());
        System.out.println("是否包含Java: " + list.contains("Java"));
        System.out.println("C++的索引: " + list.indexOf("C++"));
        // 排序
        Collections.sort(list);
        System.out.println("排序后: " + list);
        // 转换为数组
        String[] array = list.toArray(new String[0]);
    }
}

LinkedList特有操作

public class LinkedListExample {
    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<>();
        // 双端队列操作
        linkedList.addFirst("开始");
        linkedList.addLast("结束");
        linkedList.add("中间");
        // 获取首尾元素
        String first = linkedList.getFirst();
        String last = linkedList.getLast();
        // 栈操作
        linkedList.push("栈顶元素");
        String popElement = linkedList.pop();  // 弹出栈顶
        // 队列操作
        linkedList.offer("队列元素");
        String pollElement = linkedList.poll();  // 取出并移除队首
        System.out.println("LinkedList: " + linkedList);
    }
}

Set集合操作案例

HashSet基本操作

public class SetExample {
    public static void main(String[] args) {
        // 创建HashSet(无序)
        Set<String> hashSet = new HashSet<>();
        // 添加元素
        hashSet.add("苹果");
        hashSet.add("香蕉");
        hashSet.add("橘子");
        hashSet.add("苹果");  // 重复元素不会被添加
        // 判断元素是否存在
        System.out.println("是否有苹果: " + hashSet.contains("苹果"));
        // 删除元素
        hashSet.remove("香蕉");
        // 遍历(无序)
        System.out.println("HashSet遍历:");
        for (String fruit : hashSet) {
            System.out.println(fruit);
        }
        // Set运算
        Set<String> set1 = new HashSet<>(Arrays.asList("A", "B", "C"));
        Set<String> set2 = new HashSet<>(Arrays.asList("B", "C", "D"));
        // 交集
        Set<String> intersection = new HashSet<>(set1);
        intersection.retainAll(set2);
        System.out.println("交集: " + intersection);
        // 并集
        Set<String> union = new HashSet<>(set1);
        union.addAll(set2);
        System.out.println("并集: " + union);
        // 差集
        Set<String> difference = new HashSet<>(set1);
        difference.removeAll(set2);
        System.out.println("差集: " + difference);
    }
}

TreeSet(有序)

public class TreeSetExample {
    public static void main(String[] args) {
        // 自然排序
        TreeSet<Integer> numbers = new TreeSet<>();
        numbers.add(5);
        numbers.add(1);
        numbers.add(3);
        numbers.add(2);
        numbers.add(4);
        System.out.println("有序集合: " + numbers);
        // 获取范围
        System.out.println("第一个元素: " + numbers.first());
        System.out.println("最后一个元素: " + numbers.last());
        System.out.println("小于3的元素: " + numbers.headSet(3));
        System.out.println("大于等于3的元素: " + numbers.tailSet(3));
        System.out.println("1到4之间的元素: " + numbers.subSet(1, 4));
        // 自定义排序
        TreeSet<Person> persons = new TreeSet<>((p1, p2) -> 
            p1.name.compareTo(p2.name));
        persons.add(new Person("张三", 25));
        persons.add(new Person("李四", 30));
    }
    static class Person {
        String name;
        int age;
        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
}

Map集合操作案例

HashMap基本操作

public class MapExample {
    public static void main(String[] args) {
        // 创建HashMap
        Map<String, Integer> scores = new HashMap<>();
        // 添加键值对
        scores.put("张三", 95);
        scores.put("李四", 87);
        scores.put("王五", 92);
        scores.put("张三", 98);  // 更新已有的key
        // 获取值
        Integer zhangScore = scores.get("张三");
        System.out.println("张三的分数: " + zhangScore);
        // 获取默认值
        Integer zhaoScore = scores.getOrDefault("赵六", 0);
        System.out.println("赵六的分数: " + zhaoScore);
        // 判断键值是否存在
        System.out.println("是否包含张三: " + scores.containsKey("张三"));
        System.out.println("是否包含分数100: " + scores.containsValue(100));
        // 删除
        scores.remove("王五");
        // 遍历方式1: 遍历Entry
        System.out.println("遍历键值对:");
        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
        // 遍历方式2: 遍历键
        for (String key : scores.keySet()) {
            System.out.println("键: " + key + ", 值: " + scores.get(key));
        }
        // 遍历方式3: 遍历值
        for (Integer value : scores.values()) {
            System.out.println("值: " + value);
        }
        // 其他操作
        System.out.println("Map大小: " + scores.size());
        System.out.println("是否为空: " + scores.isEmpty());
        // 批量操作
        Map<String, Integer> otherScores = new HashMap<>();
        otherScores.put("赵六", 88);
        otherScores.put("钱七", 90);
        scores.putAll(otherScores);  // 合并map
    }
}

TreeMap(有序)

public class TreeMapExample {
    public static void main(String[] args) {
        // 自动按键排序
        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("C", "JavaScript");
        treeMap.put("A", "Python");
        treeMap.put("B", "Java");
        System.out.println("排序后的Map: " + treeMap);
        // 获取首尾元素
        System.out.println("第一个键: " + treeMap.firstKey());
        System.out.println("最后一个键: " + treeMap.lastKey());
        // 范围查询
        System.out.println("小于B的键: " + treeMap.headMap("B"));
        System.out.println("大于等于B的键: " + treeMap.tailMap("B"));
    }
}

集合工具类操作

Collections工具类

public class CollectionsExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6));
        // 排序
        Collections.sort(numbers);
        System.out.println("排序后: " + numbers);
        // 反转
        Collections.reverse(numbers);
        System.out.println("反转后: " + numbers);
        // 打乱顺序
        Collections.shuffle(numbers);
        System.out.println("打乱后: " + numbers);
        // 查找
        Collections.sort(numbers);
        int index = Collections.binarySearch(numbers, 5);
        System.out.println("5的索引: " + index);
        // 最大最小值
        System.out.println("最大值: " + Collections.max(numbers));
        System.out.println("最小值: " + Collections.min(numbers));
        // 填充
        Collections.fill(numbers, 0);
        System.out.println("填充后: " + numbers);
        // 复制
        List<Integer> copy = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8));
        Collections.copy(copy, Arrays.asList(10, 20, 30));
        System.out.println("复制后: " + copy);
        // 创建不可变集合
        List<String> immutableList = Collections.unmodifiableList(
            Arrays.asList("A", "B", "C"));
        // 创建同步集合(线程安全)
        List<String> syncList = Collections.synchronizedList(
            new ArrayList<>());
    }
}

实战案例:学生管理系统

import java.util.*;
public class StudentManagementSystem {
    private Map<String, Student> students;
    public StudentManagementSystem() {
        students = new HashMap<>();
    }
    // 添加学生
    public void addStudent(Student student) {
        students.put(student.getId(), student);
    }
    // 删除学生
    public boolean removeStudent(String id) {
        return students.remove(id) != null;
    }
    // 更新学生信息
    public void updateStudent(String id, String name, int age) {
        Student student = students.get(id);
        if (student != null) {
            student.setName(name);
            student.setAge(age);
        }
    }
    // 查询学生
    public Student findStudent(String id) {
        return students.get(id);
    }
    // 按年龄排序
    public List<Student> sortByAge() {
        List<Student> list = new ArrayList<>(students.values());
        Collections.sort(list, (s1, s2) -> s1.getAge() - s2.getAge());
        return list;
    }
    // 过滤特定年龄的学生
    public List<Student> filterByAge(int minAge, int maxAge) {
        List<Student> result = new ArrayList<>();
        for (Student student : students.values()) {
            if (student.getAge() >= minAge && student.getAge() <= maxAge) {
                result.add(student);
            }
        }
        return result;
    }
    // 统计各年龄段人数
    public Map<String, Integer> ageGroupStats() {
        Map<String, Integer> stats = new HashMap<>();
        for (Student student : students.values()) {
            int age = student.getAge();
            String group = age < 18 ? "未成年" : 
                          age < 30 ? "青年" : 
                          age < 50 ? "中年" : "老年";
            stats.put(group, stats.getOrDefault(group, 0) + 1);
        }
        return stats;
    }
    // 内部类
    static class Student {
        private String id;
        private String name;
        private int age;
        public Student(String id, String name, int age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }
        // getters and setters
        public String getId() { return id; }
        public String getName() { return name; }
        public int getAge() { return age; }
        public void setName(String name) { this.name = name; }
        public void setAge(int age) { this.age = age; }
        @Override
        public String toString() {
            return String.format("Student{id='%s', name='%s', age=%d}", 
                               id, name, age);
        }
    }
    // 测试
    public static void main(String[] args) {
        StudentManagementSystem system = new StudentManagementSystem();
        // 添加学生
        system.addStudent(new Student("001", "张三", 20));
        system.addStudent(new Student("002", "李四", 25));
        system.addStudent(new Student("003", "王五", 17));
        system.addStudent(new Student("004", "赵六", 35));
        // 查询
        System.out.println("查询学生001: " + system.findStudent("001"));
        // 排序
        System.out.println("按年龄排序: " + system.sortByAge());
        // 过滤
        System.out.println("20-30岁学生: " + system.filterByAge(20, 30));
        // 统计
        System.out.println("年龄统计: " + system.ageGroupStats());
    }
}

主要注意事项:

  1. 选择合适的集合类型:根据需求选择List、Set或Map
  2. 注意线程安全性:ArrayList非线程安全,可用Collections.synchronizedList()
  3. 重写equals和hashCode:自定义对象作为key时必需
  4. 避免ConcurrentModificationException:遍历时不要修改集合
  5. 注意性能:ArrayList适合随机访问,LinkedList适合插入删除

希望这些案例能帮助你更好地理解和使用Java集合框架!

抱歉,评论功能暂时关闭!