[Java - Collections.frequency()]

린린린·2025년 7월 30일

Collections.frequency()란?                                                   

✅ 기능
Collections 안에 있는 객체가 몇번 등장했는지 리턴

/**
* c 객체를 담고 있는 컬렉션 인스턴스
* o 등장 횟수를 세고 싶은 요소
*
* return o가 c 안에서 등장한 횟수(int)
*/
Collections.frequency(Collection<?> c, Object o)

✅ 기본 사용 예:

import java.util.*;

public class Main {
  public static void main(String[] args) {
      List<String> colors = Arrays.asList("red", "blue", "red", "green", "red", "blue");

      int redCount = Collections.frequency(colors, "red");
      int blueCount = Collections.frequency(colors, "blue");
      int yellowCount = Collections.frequency(colors, "yellow");

      System.out.println("red: " + redCount);     // result 3
      System.out.println("blue: " + blueCount);   // result 2
      System.out.println("yellow: " + yellowCount); // result 0
  }
}

✅ 언제 사용?

  • 리스트에서 특정 값이 몇 번 나왔는지 간단하게 셀 때
  • 빈도 기반 필터링 또는 정렬 전에 빠르게 확인
  • Map을 직접 만들고 카운트할 필요 없을 때 (간단한 경우)

✅ 추가적으로
리스트에서 가장 많이 나온 값 도출 가능

List<String> items = Arrays.asList("apple", "banana", "apple", "kiwi", "banana", "apple");

String mostFrequent = items.stream()
    .distinct()
    .max(Comparator.comparingInt(item -> Collections.frequency(items, item)))
    .orElse("없음");

System.out.println("가장 많이 나온 과일: " + mostFrequent); // result apple

이 글에서는 백준 문제 풀이 과정에서 사용한 주요 기술과 알고리즘을 설명합니다.

  • 특정 요소 찾기

실제 문제 풀이 코드는 아래 깃허브 저장소에서 확인하실 수 있습니다.
👉 깃허브 - 백준 문제 풀이 저장소


이 글과 코드를 보시고 개선할 부분이나 궁금한 점이 있으면 편하게 댓글이나 메시지로 알려주세요.💪
여러분의 피드백 덕분에 더 나은 콘텐츠를 만들 수 있습니다.
함께 성장해 나가요!

profile
개발은모르겠고일단기록

0개의 댓글