import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class MapWithSetValue {
public static void main(String[] args) {
// Map 선언
Map<String, Set<Integer>> map = new HashMap<>();
// 키 'a'에 대한 Set 추가
map.put("a", new HashSet<>());
// 키 'a'의 Set에 값 추가
map.get("a").add(1);
map.get("a").add(2);
map.get("a").add(3);
System.out.println(map); // 출력: {a=[1, 2, 3]}
}
}
map.computeIfAbsent("b", k -> new HashSet<>()).add(4);
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
Map<String, List<String>> map = new HashMap<>();
map.computeIfAbsent("fruits", k -> new ArrayList<>()).add("apple");
map.computeIfAbsent("fruits", k -> new ArrayList<>()).add("banana");
System.out.println(map); // 출력: {fruits=[apple, banana]}
map.put(k, map.getOrDefault(k, new HashSet<>()));
기본 구현
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MapWithListValue {
public static void main(String[] args) {
// Map 선언
Map<String, List<String>> map = new HashMap<>();
// 키 'fruits'에 대한 List 추가
map.put("fruits", new ArrayList<>());
// 키 'fruits'의 List에 값 추가
map.get("fruits").add("apple");
map.get("fruits").add("banana");
System.out.println(map); // 출력: {fruits=[apple, banana]}
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MapWithListValue {
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<>();
// computeIfAbsent를 사용하여 더 간결하게 값을 추가
map.computeIfAbsent("fruits", k -> new ArrayList<>()).add("apple");
map.computeIfAbsent("fruits", k -> new ArrayList<>()).add("banana");
System.out.println(map); // 출력: {fruits=[apple, banana]}
}
}