27. Map에서 조건에 맞는 요소 찾기

// 값이 2 이상인 첫 번째 요소 찾기 Optional firstMatch = map.entrySet().stream() .filter(entry -> entry.getValue() >= 2) .findFirst(); // 값이 2 이상인 모든 요소 찾기 List allMatches = map.entrySet().stream() .filter(entry -> entry.getValue() >= 2) .collect(Collectors.toList());

26. Map의 요소를 Stream으로 변환하기

// EntrySet을 Stream으로 변환하기 Stream entryStream = map.entrySet().stream(); // KeySet을 Stream으로 변환하기 Stream keyStream = map.keySet().stream(); // ValueSet을 Stream으로 변환하기 Stream valueStream = map.values().stream();

25. Map의 요소를 Set으로 변환하기

// 키와 값 모두 포함한 EntrySet을 Set으로 변환하기 Set entrySet = map.entrySet(); // 키만 포함한 KeySet을 Set으로 변환하기 Set keySet = map.keySet(); // 값만 포함한 ValueSet을 Set으로 변환하기 Set valueSet = new HashSet(map.values());

24. Map에서 키/값 모두 이용하여 필터링하기

// 키/값 모두 이용하여 값이 2 이상인 요소만 필터링 Map filteredMap = map.entrySet().stream() .filter(entry -> entry.getKey().startsWith("a") && entry.getValue() >= 2) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

23. Map에서 키/값 모두 이용하여 정렬하기

// 키/값 모두 이용하여 오름차순 정렬하기 List entryList = new ArrayList(map.entrySet()); entryList.sort(Map.Entry.comparingByKey().thenComparing(Map.Entry.comparingByValue())); Map sortedMap = new LinkedHashMap(); for (Map.Entry entry : entryList) { sortedMap.put(entry.getKey(), entry.getValue()); }

22. Map에서 최대값/최소값 찾기

// 최댓값 찾기 int maxValue = map.values().stream().mapToInt(Integer::intValue).max().orElse(Integer.MIN_VALUE); // 최솟값 찾기 int minValue = map.values().stream().mapToInt(Integer::intValue).min().orElse(Integer.MAX_VALUE);

21. Map 요소의 키/값 검증

// 키 검증 boolean isValidKey = map.keySet().stream().allMatch(key -> key != null && key.length() > 0); // 값 검증 boolean isValidValue = map.values().stream().allMatch(value -> value > 0);

20. Map을 사용하여 Enum과 연결하기

// Enum과 Map을 사용하여 상수값과 문자열 값을 연결하기 enum Fruit { APPLE("apple"), BANANA("banana"), CHERRY("cherry"); private final String name; private static final Map map = new HashMap(); static { for (Fruit fruit : values()) { map.put(fruit.getName(), fruit); } } Fruit(String name) { this.name = name; } public String getName() { return name; } public static Fruit get(String name) { return map.get(name); } } ..

19. Map의 키/값 순서 유지하기

// LinkedHashMap을 사용하여 키/값 순서 유지하기 Map linkedHashMap = new LinkedHashMap(); linkedHashMap.put("apple", 1); linkedHashMap.put("banana", 2); linkedHashMap.put("cherry", 3);

18. Map의 키나 값 중 하나의 값만 추출

// key 값만 추출 Set keySet = map.keySet(); // value 값만 추출 Collection values = map.values();

17. Map 요소의 부분 집합 검색

// key가 "a"로 시작하는 요소 추출 Map subMap = map.entrySet().stream() .filter(entry -> entry.getKey().startsWith("a")) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

16. Map 요소 처리 - forEach

// 모든 요소에 대해 처리 (BiConsumer 사용) map.forEach((key, value) -> System.out.println(key + " : " + value));