pollFirstEntry( )

Titanium·2025년 1월 10일

동작 원리

  1. pollFirstEntry() 메서드:

    • TreeMap에서 가장 낮은 키를 가진 Map.Entry 객체를 반환.
    • 반환된 엔트리는 TreeMap에서 제거됩니다.
    • 만약 TreeMap이 비어 있다면 null을 반환합니다.
  2. 결과적으로:

    • 호출 시 TreeMap에서 가장 첫 번째 키-값 쌍을 가져옴과 동시에 TreeMap에서 삭제됩니다.

예제

TreeMap 상태:

TreeMap<Integer, String> scores = new TreeMap<>();
scores.put(75, "박길순");
scores.put(80, "김자바");
scores.put(87, "홍길동");
scores.put(95, "신용권");
scores.put(98, "이동수");

코드 실행:

Map.Entry<Integer, String> entry = scores.pollFirstEntry();
System.out.println(entry.getKey() + "-" + entry.getValue());
System.out.println(scores);

실행 결과:

75-박길순
{80=김자바, 87=홍길동, 95=신용권, 98=이동수}

정리

  • pollFirstEntry()가장 낮은 키를 가진 엔트리를 반환하면서 TreeMap에서 해당 엔트리를 삭제합니다.
  • 조회와 삭제가 동시에 이루어지므로 반복적으로 호출하면 TreeMap의 엔트리들을 하나씩 처리할 수 있습니다.

이 메서드는 TreeMap의 데이터를 정렬된 순서로 처리(삭제)하고자 할 때 유용합니다. 😊

profile
핵심먼저

0개의 댓글