Guava는 Google에서 개발한 자바 라이브러리로, 다양한 기능을 제공하여 개발자들의 작업을 보다 간편하고 효율적으로 만들어줍니다. 컬렉션 기반의 유틸리티 클래스는 Guava의 중요한 기능 중 하나로, 다양한 컬렉션 작업을 수행할 수 있는 다양한 유틸리티 메서드를 제공합니다.
1. Immutable Collections
Guava의 Immutable Collections(불변 컬렉션)은 변경할 수 없는 컬렉션을 생성하는 메서드를 제공합니다. 이를 통해 안전성과 성능을 향상시킬 수 있습니다. ImmutableList
, ImmutableSet
, ImmutableMap
등 다양한 불변 컬렉션 클래스가 제공됩니다.
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
public class ImmutableCollectionsExample {
public static void main(String[] args) {
ImmutableList<String> list = ImmutableList.of("apple", "banana", "orange");
ImmutableSet<Integer> set = ImmutableSet.of(1, 2, 3);
ImmutableMap<String, Integer> map = ImmutableMap.of("key1", 1, "key2", 2);
System.out.println(list);
System.out.println(set);
System.out.println(map);
}
}
2. Multimaps
Multimap은 Guava에서 제공하는 Map의 확장 형태입니다. Key에 여러 개의 Value를 매핑할 수 있습니다. 다양한 Multimap 구현체는 ArrayListMultimap
, HashMultimap
, TreeMultimap
등이 있습니다.
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class MultimapExample {
public static void main(String[] args) {
Multimap<String, String> multiMap = ArrayListMultimap.create();
multiMap.put("key1", "value1");
multiMap.put("key1", "value2");
multiMap.put("key2", "value3");
System.out.println(multiMap.get("key1"));
System.out.println(multiMap.get("key2"));
}
}
3. BiMap
BiMap은 Key와 Value가 서로 일대일 대응인 맵입니다. Key와 Value를 양방향으로 조회할 수 있습니다. HashBiMap
, EnumBiMap
등 다양한 BiMap 구현체가 제공됩니다.
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
public class BiMapExample {
public static void main(String[] args) {
BiMap<String, Integer> biMap = HashBiMap.create();
biMap.put("one", 1);
biMap.put("two", 2);
biMap.put("three", 3);
System.out.println(biMap.get("one"));
System.out.println(biMap.inverse().get(2));
}
}
4. Table
Table은 두 개의 Key로 2차원 맵을 생성하는 기능을 제공합니다. HashBasedTable
, TreeBasedTable
등 다양한 Table 구현체가 제공됩니다.
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
public class TableExample {
public static void main(String[] args) {
Table<Integer, Integer, String> table = HashBasedTable.create();
table.put(1, 1, "value1");
table.put(1, 2, "value2");
table.put(2, 1, "value3");
System.out.println(table.get(1, 1));
System.out.println(table.row(1));
System.out.println(table.column(1));
}
}
위의 예제 코드는 Guava에서 제공하는 컬렉션 기반 유틸리티 클래스의 일부를 보여줍니다. 다양한 기능과 메서드가 더 있으니, 자세한 내용은 Guava의 공식 문서를 참조하시기 바랍니다.
참고 자료
- Guava - Google Developers
- Guava - Immutable Collections
- Guava - NewCollectionTypesExplained
- Guava - Table