문자열 "the quick the lazy the dog quick"에서 단어별 빈도를 세고, 빈도 내림차순(같으면 단어 오름차순)으로 상위 2개를 출력하라. Map.merge와 Comparator 조합을 사용할 것.
import java.util.*;
public class Main {
public static void main(String[] args) {
String text = "the quick the lazy the dog quick";
Map<String, Integer> freq = new HashMap<>();
for (String w : text.split(" ")) freq.merge(w, 1, Integer::sum);
List<Map.Entry<String, Integer>> entries = new ArrayList<>(freq.entrySet());
entries.sort(Map.Entry.<String, Integer>comparingByValue(Comparator.reverseOrder())
.thenComparing(Map.Entry.comparingByKey()));
for (int i = 0; i < 2; i++) {
System.out.println(entries.get(i).getKey() + "=" + entries.get(i).getValue());
}
// 출력:
// the=3
// quick=2
}
}LinkedHashMap을 상속하지 않고 컴포지션으로, 최대 3개의 최근 본 상품 ID를 유지하는 RecentlyViewed 클래스를 만들어라. view(String id) 호출 시 이미 있으면 최신으로 갱신, 초과 시 가장 오래된 것을 제거하며, ids()는 오래된 것부터 최신 순 리스트를 반환한다.
view("A"), view("B"), view("C"), view("A"), view("D") 후 ids()가 [C, A, D]여야 한다.
import java.util.*;
class RecentlyViewed {
private final int capacity;
private final LinkedHashMap<String, Boolean> map = new LinkedHashMap<>(16, 0.75f, true);
RecentlyViewed(int capacity) { this.capacity = capacity; }
void view(String id) {
map.put(id, Boolean.TRUE); // accessOrder → 맨 뒤로
if (map.size() > capacity) {
String eldest = map.keySet().iterator().next(); // 맨 앞 = 가장 오래된 것
map.remove(eldest);
}
}
List<String> ids() { return new ArrayList<>(map.keySet()); }
}
public class Main {
public static void main(String[] args) {
RecentlyViewed rv = new RecentlyViewed(3);
for (String id : List.of("A", "B", "C", "A", "D")) rv.view(id);
System.out.println(rv.ids()); // 출력: [C, A, D]
}
}허용된 상태 전이 CREATED→PAID, PAID→SHIPPED, PAID→CANCELLED, SHIPPED→DELIVERED를 Map<String, Set<String>>으로 정의하고, canTransit(from, to)를 작성하라. 없는 상태에서 조회해도 NPE가 나면 안 된다. CREATED→PAID(true), PAID→DELIVERED(false), UNKNOWN→PAID(false)를 출력하라.
import java.util.Map;
import java.util.Set;
public class Main {
static final Map<String, Set<String>> TRANSITIONS = Map.of(
"CREATED", Set.of("PAID"),
"PAID", Set.of("SHIPPED", "CANCELLED"),
"SHIPPED", Set.of("DELIVERED")
);
static boolean canTransit(String from, String to) {
return TRANSITIONS.getOrDefault(from, Set.of()).contains(to); // 없는 키 → 빈 Set
}
public static void main(String[] args) {
System.out.println(canTransit("CREATED", "PAID")); // 출력: true
System.out.println(canTransit("PAID", "DELIVERED")); // 출력: false
System.out.println(canTransit("UNKNOWN", "PAID")); // 출력: false
}
}