[Java] Map · enum · 람다

배창민·2025년 9월 18일
post-thumbnail

Java Map · enum · 람다


1) Map

개념

  • Map: 키(Key) - 값(Value) 쌍 저장. 키 중복 X, 값 중복 O.
  • 대표 구현체: HashMap, Hashtable, TreeMap.

HashMap 핵심

  • 해시 테이블 기반 → 검색/조회 빠름.
  • 키 중복 시 덮어씀, 값 중복 가능.
// 선언/기본 조작
Map<Object, Object> hmap = new HashMap<>();
hmap.put("one", new Date());
hmap.put(12, "red apple");
hmap.put(12, "yellow banana"); // 같은 키 → 값 덮어씀
hmap.remove(12);
Object v = hmap.get("one");
System.out.println(hmap.size());

순회(3가지 패턴)

Map<String, String> map = Map.of(
  "one","java 8","two","oracle 11g","three","jdbc"
);

// 1) keySet + iterator / for-each
for (String k : map.keySet()) System.out.println(k + " = " + map.get(k));

// 2) values()
for (String v : map.values()) System.out.println(v);

// 3) entrySet()  ← 가장 선호
for (Map.Entry<String,String> e : map.entrySet())
  System.out.println(e.getKey() + " : " + e.getValue());

Properties

  • (String, String) 전용 해시 테이블.
  • 환경설정을 파일로 저장/로드할 때 주로 사용.
Properties prop = new Properties();
prop.setProperty("driver","oracle.jdbc.driver.OracleDriver");
prop.setProperty("url","jdbc:oracle:thin:@127.0.0.1:1521:xe");
prop.setProperty("user","student");
prop.setProperty("password","student");

// 저장
prop.store(new FileOutputStream("driver.dat"), "jdbc driver");
prop.store(new FileWriter("driver.txt"), "jdbc driver");
prop.storeToXML(new FileOutputStream("driver.xml"), "jdbc driver");

// 로드
Properties p2 = new Properties();
p2.load(new FileInputStream("driver.dat"));
p2.load(new FileReader("driver.txt"));
p2.loadFromXML(new FileInputStream("driver.xml"));
p2.list(System.out);

2) enum

왜 쓰나?

  • 타입 안전성(컴파일 타임 체크), 가독성(이름 그대로 출력), 순회 및 부가정보(필드/메소드) 가능.
  • 정수/문자열 상수 패턴의 단점을 해결.

선언/사용

public enum Foods {
  MEAL_STEW, MEAL_SOUP, DRINK_LATTE
}

Foods f = Foods.MEAL_STEW;
System.out.println(f);          // MEAL_STEW

필드/생성자/메소드 추가

public enum Foods {
  MEAL_STEW(0,"앙버터김치찜"),
  DRINK_LATTE(1,"열무김치라떼");

  private final int code;
  private final String label;

  Foods(int code, String label){ this.code=code; this.label=label; }
  public int getCode(){ return code; }
  public String getLabel(){ return label; }

  @Override public String toString(){ return label; } // 출력 커스터마이즈
}

자주 쓰는 메소드

// values(): 전체 순회
for (Foods f : Foods.values()) System.out.println(f);

// valueOf(): 이름으로 찾기
Foods x = Foods.valueOf("MEAL_STEW");

// ordinal(): 선언 순서 인덱스
int idx = Foods.DRINK_LATTE.ordinal();

// name()/toString()
String n1 = Foods.MEAL_STEW.name();
String n2 = Foods.MEAL_STEW.toString();

EnumSet (빠른 Set 구현)

EnumSet<Foods> all = EnumSet.allOf(Foods.class);
EnumSet<Foods> some = EnumSet.of(Foods.MEAL_STEW);
EnumSet<Foods> except = EnumSet.complementOf(EnumSet.of(Foods.DRINK_LATTE));

3) 람다 & 함수형 인터페이스

람다식 기본

// 형식
() -> { /* 본문 */ }
x -> x * x                   // 매개 1개면 () 생략
(x, y) -> x + y              // 본문 1문장이면 {}/return 생략
  • 하나의 추상 메소드만 가진 인터페이스(= 함수형 인터페이스)에 대입해 사용
  • 표준 패키지: java.util.function

대표 인터페이스 요약 + 예제

Consumer: 입력만 받고 리턴 없음

Consumer<String> c = s -> System.out.println(s + " 입력됨");
c.accept("람다");

Supplier: 입력 없음, 값 제공

BooleanSupplier s = () -> ((int)(Math.random()*10)+1) % 2 == 0;
System.out.println(s.getAsBoolean());

Function: 입력 → 다른 타입으로 매핑

Function<Integer,String> f = i -> String.valueOf(i);
ToIntFunction<String> g = Integer::parseInt;

Operator: 입력 → 같은 타입으로 연산/반환

int[] arr = {64,90,80,92,100};
IntBinaryOperator maxOp = Math::max;
int max = Arrays.stream(arr).reduce(maxOp).orElseThrow();

Predicate: 입력을 판별(boolean)

IntPredicate pass = n -> n >= 80;
System.out.println(pass.test(87));  // true

기억법: CSFOP
C(Consumer) 입력만, S(Supplier) 공급, F(Function) 매핑, O(Operator) 동형연산, P(Predicate) 판별


4) 메소드 참조 (Method Reference)

  • 람다를 더 줄인 표기. 타입/매개수/반환형이 함수형 인터페이스와 호환되어야 함.

  • 형식

    • 인스턴스 메소드: 객체참조::메소드
    • 정적 메소드: 클래스명::정적메소드
    • 생성자: 클래스명::new
// 1) 매개변수 메소드 참조
BiFunction<String,String,Boolean> eq = String::equals;
System.out.println(eq.apply("A","A")); // true

// 2) 생성자 참조
class Member { Member(String id){ this.id=id; } String id; }
Function<String, Member> maker = Member::new;
Member m = maker.apply("Lambda");

핵심 정리

  • Map 순회entrySet()이 가장 깔끔/효율적.
  • enum에 의미 있는 필드/메소드를 부여해 도메인 모델링에 적극 활용.
  • 람다/메소드 참조보일러플레이트 최소화, java.util.function 조합을 익혀두면 컬렉션/스트림 처리에 강력해짐.
  • EnumSet은 enum 전용 Set로 가볍고 빠름.
profile
개발자 희망자

0개의 댓글