Notice
Recent Posts
Recent Comments
«   2026/04   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

Spring & Java

컬렉션 ( Collection ) 본문

JAVA 개념 확장

컬렉션 ( Collection )

dev.hyuck 2025. 12. 15. 11:09

예외 ( Exception )과 예외처리 (try-catch)

● Optional - null을 다루는 법

 

학습 키워드 점검

 

컬렉션 - 자료구조들을 쉽게 사용할 수 있도록 인터페이스와 구현체를 제공하는 집합

ArrayList - 순서유지, 중복가능

HashSet - 순서없음, 중복불가

HashMap - Key-Value을 저장하는 자료구조, 순서없음

 

컬렉션 ( Collection ) 이란?

컬렉션 ( Collection ) 이 무엇인지 학습해 봅시다.

● 프로그래밍 세계에는 다양한 자료구조가 존재합니다.

● 자바 컬렉션 프레임워크는 이러한 자료구조들을 쉽게 사용할 수 있도록 인터페이스와 구현체 

( ArrayList, HashSet, HashMpa 등)를 제공하는 집합입니다.

● 컬렉션을 통해 데이터 저장, 조회, 삭제, 정렬 등 다양한 기능을 간편하게 구현할 수 있습니다.

● 배열과 다르게 컬렉션은 길이를 동적으로 변경할 수 있습니다.

(추가 삭제 시 우연하게 길이가 변경됩니다. )

 

배열의 한계

● 배열은 크기가 고정되어 있어서 한번 설정하면 길이를 변경할 수 없습니다.

> 배열의 길이 초과 시 에러가 발생합니다.

● 자바에서는 다양한 컬렉션 클래스 ( ArraryList, HashSet, HashMap 등) 를 제공합니다.

● 컬렉션 객체를 활용해 데이터들을 저장하고 관리할 수 있습니다.

// 배열은 길이가 고정됨
int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40; // ❌ 요소 추가시 에러발생

<< 선언 방법 >>
컬렉션객체<자료형> 변수이름 = new 컬렉션객체<자료형>();

// 객체<다룰 데이터: 정수> 변수이름 = new 컬렉션객체생성자<정수>();
ArrayList<Integer> arrayList = new ArrayList<Integer>();

ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(10);
arrayList.add(20);
arrayList.add(30);
arrayList.add(40); // ✅ 정상 동작 (길이 제한 없음)

 

컬렉션 종류와 특징

인터페이스 특징 구현체
List 순서 유지, 중복 허용 ArrayList
Set 순서 없음, 중복 불가  HashSet
Map 키 - 값 구조, 키 중복 불가 HashMap

 

List 인터페이스를 구현한 ArrayList

List 인터페이스를 구현한 ArrayList를 활용해 봅시다.

● ArrayList는 요소의 순서를 유지하고 중복된 값을 저장할 수 있는 자료구조 입니다.

● 요소 추가 > add ( " 값 " )

● 요소 조회 > get ( 인덱스 )

● 요소 제거 > remove ( " 값 " )

● 대표적인 구현체로는 ArrayList, LinkedList가 있습니다.

// List 를 구현한 ArrayList
ArrayList<String> names = new ArrayList<>();
names.add("Spartan");      // 1 번째 요소 추가
names.add("Steve");        // 2 번째 요소 추가
names.add("Isac");         // 3 번째 요소 추가
names.add("1");
names.add("2");

 // ✅ 순서 보장
System.out.println("names = " + names);

// ✅ 중복 데이터 허용
names.add("Spartan");
System.out.println("names = " + names);

// ✅ 단건 조회
System.out.println("1 번째 요소 조회: " + names.get(0)); // 조회 Spartan

// ✅ 데이터 삭제
names.remove("Steve"); 
System.out.println("names = " + names);

 

Set 인터페이스를 구현한 HashSet

Set 인터페이스를 구현한 Hashset을 활용해 봅시다.

● HashSet은 순서를 유지하지 않고 중복을 허용하지 않습니다.

> 순서를 보장하지 않기 때문에 Get을 지원하지 않습니다.

● 요소 추가 > add ( " 값 " )

● 요소 제거 > remove ( " 값 " )

● 대표적인 구현체로는 HashSet, TreeSet이 있습니다.

// Set 을 구현한 HashSet
HashSet<String> uniqueNames = new HashSet<>();

// ✅ 추가
uniqueNames.add("Spartan");
uniqueNames.add("Steve");
uniqueNames.add("Isac");
uniqueNames.add("1");
uniqueNames.add("2");

// ⚠️ 순서를 보장 안함
System.out.println("uniqueNames = " + uniqueNames); 
uniqueNames.get(0); // ❌ get 사용 불가

// ⚠️ 중복 불가
uniqueNames.add("Spartan");
System.out.println("uniqueNames = " + uniqueNames); 

// ✅ 제거
uniqueNames.remove("Spartan");
System.out.println("uniqueNames = " + uniqueNames);

 

Map 인터페이스를 구현한 HashMap

Map 인터페이스를 구현한 HashMpa을 활용해 봅시다.

● HashMap은 키 (key) - 값 (Value) 구조로 데이터를 저장합니다. ( 키 : 값 )

● 키 ( Key ) 는 중복될 수 없지만 값 ( Value ) 은 중복 가능합니다.

● 순서를 보장하지 않습니다.

● 요소 추가 > put ( " 키 " , 값 )

● 요소 조회 > get ( " 키 " )

● 요소 제거 > remove( " " )

● 키 확인 > KeySet

● 값 확인 > value ()
● 대표적인 구현체로는 HashMap, TreeMap이 있습니다.

// Map 을 구현한 HashMap
HashMap<String, Integer> memberMap = new HashMap<>();

// ✅ 추가
memberMap.put("Spartan", 15);
memberMap.put("Steve", 15); // ✅ 값은 중복 가능
memberMap.put("Isac", 1);
memberMap.put("John", 2);
memberMap.put("Alice", 3);

// ⚠️ 순서 보장 안함 
System.out.println("memberMap = " + memberMap);

// ⚠️ 키 중복 불가: 값 덮어쓰기 발생
memberMap.put("Alice", 5);
System.out.println("memberMap = " + memberMap);

// ✅ 조회: 15
System.out.println(memberMap.get("Steve"));

// ✅ 삭제 가능
memberMap.remove("Spartan"); 
System.out.println("memberMap = " + memberMap);

// ✅ 키 확인
Set<String> keys = memberMap.keySet();
System.out.println("keys = " + keys);

// ✅ 값 확인
Collection<Integer> values = memberMap.values();
System.out.println("values = " + values);

 

package Study13;

import java.util.*;
// 메서드 add / get / remove

public class Main {

    public static void main(String[] args) {

        // ArrayList 활용
        ArrayList<String> names = new ArrayList<>();

        // 데이터 추가
        names.add("Spartan");
        names.add("Steve");
        names.add("Isac");
        names.add("1");
        names.add("2");
        System.out.println("names : " + names);

        // 중복 데이터 허용
        names.add("Spartan");
        System.out.println("names : " + names);

        // 데이터 단건 조회
        String name1 = names.get(0);
        System.out.println("name 1: " + name1);

        // 데이터 삭제
        names.remove("Steve");
        System.out.println("names : " + names);

        // HashSet 사용방법 >> 순서를 보장하지 않아 Get의 메서드를 활용할 수 없습니다.
        // HashSet >> 중복 데이터 사용이 불가능 합니다.
        // 순서를 보장하지 않는다 ? uniqueNames : [1, 2, Spartan, Steve, Isac] 이런식으로 0 -> 1 아니다.
        HashSet<String> uniqueNames = new HashSet<>();
        uniqueNames.add("Spartan");

        // 데이터 추가
        uniqueNames.add("Spartan");
        uniqueNames.add("Steve");
        uniqueNames.add("Isac");
        uniqueNames.add("1");
        uniqueNames.add("2");
        System.out.println("uniqueNames : " + uniqueNames);

        // 데이터 제거
        uniqueNames.remove("Spartan");
        System.out.println("uniqueNames : " + uniqueNames);


        // HashMap 활용
        // < 키("") , 값(0) > -> 저장

        HashMap<String, Integer> memberMap = new HashMap<>();

        // 데이터 추가
        memberMap.put("Spartan", 15);
        memberMap.put("Steve", 10);
        memberMap.put("Isac", 1);
        memberMap.put("John", 2);
        memberMap.put("Alice", 3);
        System.out.println("memberMap : " + memberMap);

        // 키 중복 불가: 값이 덮어 쓰기 발생
        memberMap.put("Alice", 5);
        System.out.println("memberMap : " + memberMap);

        // 단건 조회
        Integer sprtanNum = memberMap.get("Spartan");
        System.out.println("sprtanNum : " + sprtanNum);

        // 삭제
        memberMap.remove("Spartan");
        System.out.println("memberMap : " + memberMap);

        // 키 확인
        Set<String> keySet = memberMap.keySet();
        System.out.println("KeySet : " + keySet);

        // 값 확인
        Collection<Integer> values = memberMap.values();
        System.out.println("values : " + values);

    }
}

 

public class Main {

    public static void main(String[] args) {

        Cart cart = new Cart();
        Product onion = new Product("양파", 3000);
        Product apple = new Product("사과", 10000);
        Product fish = new Product("생선", 12000);
        Product tofu = new Product("두부", 2000);


        // 장바구니에 상품 추가
        System.out.println("장바구니 상품 추가: ");
        cart.addProduct(onion);
        cart.addProduct(apple);
        cart.addProduct(fish);
        cart.addProduct(tofu);
        System.out.println();

        //  장바구니 상품 조회
        System.out.println("장바구니 상품 조회: ");
        cart.printCart();
        System.out.println();

        // 장바구니 총 금액 조회
        System.out.println("장바구니 총 금액 조회: ");
        cart.calculateTotalPrice();
        System.out.println();

        // 장바구니 상품 제거(사과)
        System.out.println("장바구니에서 사과 제거: ");
        cart.removeProduct("사과");
        System.out.println();

        //  장바구니 상품 조회
        System.out.println("장바구니 상품 조회: ");
        cart.printCart();
        System.out.println();

        // 장바구니 총 금액 조회
        System.out.println("장바구니 총 금액 조회: ");
        cart.calculateTotalPrice();
        System.out.println();
    }
}

import java.util.ArrayList;
import java.util.List;

public class Cart {

    // 속성
    private List<Product> cart = new ArrayList<>();

    // 생성자

    // 기능
    // 상품 추가 기능
    public  void addProduct(Product product) {
        cart.add(product);
        System.out.println(product.getName() + " 가 장바구니에 추가 되었습니다.");
    }

    // 상품 제거 기능
    public void removeProduct(String removeProductName) {
        boolean removed = false;

        for (Product product : cart) {
            String foundProductName = product.getName();
            if (foundProductName.equals(removeProductName)) {
                cart.remove(product);
                removed = true;
                System.out.println(product.getName() + "가 장바구니에서 제거 되었습니다.");
                break;
            }
        }
        if (!removed) {
            System.out.println("해당 상품이 장바구니에 없습니다.");
        }
    }

    // 장바구니 목록 출력 기능
    public void printCart() {
        if (cart.isEmpty()) {
            System.out.println("장바구니가 비어 있습니다.");
        } else {
            for (Product product : cart) {
                System.out.println(product.getName() + ": " + product.getPrice());
            }
        }
    }

    // 장바구니 총 상품 가격 조회 기능
    public void calculateTotalPrice() {
        int total = 0;
        for (Product product : cart) {
            total += product.getPrice();
        }
        System.out.println("총 금액은: " + total);
    }
}

public class Product {
    // 속성
    private String name;
    private int price;

    // 생성자
    public Product(String name, int price) {
        this.name = name;
        this.price = price;
    }

    // 기능
    public String getName() {
        return this.name;
    }

    public int getPrice() {
        return this.price;
    }
}

'JAVA 개념 확장' 카테고리의 다른 글

스트림 ( Stream )  (0) 2025.12.18
람다 (Lambda)  (0) 2025.12.17
제네릭 ( Generic )  (0) 2025.12.15
Optional - null을 다루는 법  (0) 2025.12.12
예외 ( Exception )과 예외처리 (try-catch)  (0) 2025.12.12