ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • ChatGPT로 Java 공부하기 #3 자바 컬렉션 프레임워크와 주요 클래스
    ChatGPT로 공부하기/Java 2024. 11. 19. 17:25

     

    자바 컬렉션 프레임워크와 주요 클래스


    1. 자바 컬렉션 프레임워크란?

    정의

    자바 컬렉션 프레임워크(Java Collections Framework, JCF)는 데이터를 효율적으로 저장하고 관리하기 위해 제공되는 클래스와 인터페이스의 집합입니다.

    주요 특징

    • 데이터 구조 구현: 리스트, 스택, 큐, 집합 등 다양한 자료구조 제공
    • 표준화: 일관된 API를 제공
    • 유연성: 다양한 데이터 타입과 크기를 동적으로 처리 가능
    • 알고리즘 제공: 정렬, 검색, 순회 등 기본적인 알고리즘 내장

    2. 주요 인터페이스와 클래스

    2.1 주요 인터페이스

    1. List: 순서가 있는 데이터의 집합 (중복 허용)
      • 주요 구현 클래스: ArrayList, LinkedList
    2. Set: 중복을 허용하지 않는 데이터의 집합
      • 주요 구현 클래스: HashSet, TreeSet
    3. Queue: FIFO(First In First Out) 구조의 데이터 집합
      • 주요 구현 클래스: PriorityQueue, LinkedList
    4. Map: 키-값 쌍으로 데이터를 저장 (키는 중복 불가)
      • 주요 구현 클래스: HashMap, TreeMap

    2.2 주요 클래스

    2.2.1 ArrayList

    배열 기반의 리스트로, 크기를 동적으로 조정 가능하며 순차적인 데이터 접근에 최적화되어 있습니다.

    import java.util.ArrayList;
    
    public class ArrayListExample {
        public static void main(String[] args) {
            ArrayList<String> names = new ArrayList<>();
            names.add("Alice");
            names.add("Bob");
            names.add("Charlie");
    
            // 데이터 출력
            for (String name : names) {
                System.out.println(name);
            }
    
            // 특정 인덱스의 데이터 접근
            System.out.println("첫 번째 이름: " + names.get(0));
    
            // 데이터 제거
            names.remove("Bob");
            System.out.println("Bob 제거 후: " + names);
        }
    }
    
    

    2.2.2 HashSet

    중복을 허용하지 않으며 순서가 없는 데이터 구조입니다.

    내부적으로 HashMap을 사용하여 빠른 검색과 삽입을 지원합니다.

    import java.util.HashSet;
    
    public class HashSetExample {
        public static void main(String[] args) {
            HashSet<Integer> numbers = new HashSet<>();
            numbers.add(1);
            numbers.add(2);
            numbers.add(2); // 중복된 값은 무시
    
            // 데이터 출력
            for (int number : numbers) {
                System.out.println(number);
            }
        }
    }
    
    

    2.2.3 HashMap

    키-값 쌍으로 데이터를 저장하며, 키의 중복을 허용하지 않습니다.

    import java.util.HashMap;
    
    public class HashMapExample {
        public static void main(String[] args) {
            HashMap<String, String> capitals = new HashMap<>();
            capitals.put("USA", "Washington");
            capitals.put("France", "Paris");
            capitals.put("Korea", "Seoul");
    
            // 데이터 출력
            for (String country : capitals.keySet()) {
                System.out.println(country + "의 수도는 " + capitals.get(country));
            }
        }
    }
    
    

    2.2.4 PriorityQueue

    우선순위에 따라 데이터를 정렬하며, 기본적으로 최소값이 가장 먼저 출력됩니다.

    import java.util.PriorityQueue;
    
    public class PriorityQueueExample {
        public static void main(String[] args) {
            PriorityQueue<Integer> queue = new PriorityQueue<>();
            queue.add(10);
            queue.add(5);
            queue.add(20);
    
            // 데이터 출력 (오름차순)
            while (!queue.isEmpty()) {
                System.out.println(queue.poll()); // 가장 작은 값부터 제거
            }
        }
    }
    
    

    3. 실무 적용 예제: 학생 관리 시스템

    요구사항

    1. 학생의 이름과 점수를 저장
    2. 점수를 기준으로 정렬
    3. 특정 점수 이상의 학생 목록 출력

    코드 구현

    import java.util.*;
    
    class Student {
        String name;
        int score;
    
        public Student(String name, int score) {
            this.name = name;
            this.score = score;
        }
    
        @Override
        public String toString() {
            return name + ": " + score;
        }
    }
    
    public class StudentManagement {
        public static void main(String[] args) {
            // 학생 데이터 저장
            List<Student> students = new ArrayList<>();
            students.add(new Student("Alice", 85));
            students.add(new Student("Bob", 90));
            students.add(new Student("Charlie", 70));
    
            // 점수 기준으로 정렬
            students.sort(Comparator.comparingInt(s -> s.score));
            System.out.println("정렬된 학생 목록:");
            for (Student student : students) {
                System.out.println(student);
            }
    
            // 특정 점수 이상의 학생 출력 (Stream API 활용)
            int threshold = 80;
            System.out.println("\\n점수가 " + threshold + " 이상인 학생:");
            students.stream()
    				        // 조건에 맞는 학생 필터링
                    .filter(student -> student.score >= threshold) 
                    // 각 학생 출력
                    .forEach(System.out::println);                 
        }
    }
    
    

     

Designed by Tistory.