ImmutableMap, ImmutableSet, ImmutableList 에서 자주 쓰는 예제이다. of() 또는 build()를 이용해서 만든다. 


예제

import java.util.List;
import java.util.Set;

import org.apache.commons.collections.MapUtils;
import org.junit.Test;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

public class GuavaTest {

@Test
public void test() {
// ImmutableMap 예제
ImmutableMap<Integer, Integer>
mapOfIntegerAndInteger = ImmutableMap.of(20000024, 2, 20000026, 3, 20000052, 1, 20000059, 2, 20000063, 3);
MapUtils.debugPrint(System.
out, "test", mapOfIntegerAndInteger);

ImmutableMap<String, Integer>
mapOfStringAndInteger = ImmutableMap.of("Samuel", 2, "Jason", 3, "Kalley", 1, "Bono", 2, "Kelly", 3);
MapUtils.debugPrint(System.
out, "test1", mapOfStringAndInteger);

//너무 많은 map을 만들 것 같으면, builder를 사용한다.
ImmutableMap<String,String>
mapByBuilder = ImmutableMap.<String, String>builder()
    .put(
"key1", "value1")
    .put(
"key2", "value2")
    .build();
MapUtils.debugPrint(System.
out, "test2", mapByBuilder);

// ImmutableList 예제
List<String>
list = ImmutableList.of("Samuel", "Jason", "Kalley");
System.
out.println(list);

List<String>
listByBuilder = ImmutableList.<String>builder()
.add(
"Samuel")
.add(
"Hally")
.add(
"Brian")
.build();
System.
out.println(listByBuilder);

// ImmutableSet 예제
Set<String>
set = ImmutableSet.of("Samuel", "Jason", "Samuel");
System.
out.println(set);

Set<String>
setByBuilder = ImmutableSet.<String>builder()
.add(
"Samuel")
.add(
"Samuel")
.build();
System.
out.println(setByBuilder);
}

}



결과

test = 

{

    20000024 = 2 java.lang.Integer

    20000026 = 3 java.lang.Integer

    20000052 = 1 java.lang.Integer

    20000059 = 2 java.lang.Integer

    20000063 = 3 java.lang.Integer

} com.google.common.collect.RegularImmutableMap

test1 = 

{

    Samuel = 2 java.lang.Integer

    Jason = 3 java.lang.Integer

    Kalley = 1 java.lang.Integer

    Bono = 2 java.lang.Integer

    Kelly = 3 java.lang.Integer

} com.google.common.collect.RegularImmutableMap

test2 = 

{

    key1 = value1 java.lang.String

    key2 = value2 java.lang.String

} com.google.common.collect.RegularImmutableMap

[Samuel, Jason, Kalley]

[Samuel, Hally, Brian]

[Samuel, Jason]

[Samuel]



Posted by 김용환 '김용환'

댓글을 달아 주세요