Development/Code

자바 개발자를 위한: 생산성을 향상시킬 10가지 Guava 기능

Danny Seo 2024. 6. 28. 17:23

자바 개발자를 위한, 코딩 방식을 혁실할 10가지 구아바 기능

자바 개발자들은 항상 코드를 더 깔끔하고 효율적이며 유지보수가 용이하게 만들어주는 라이브러리를 찾고 있습니다.

 

구글 구아바(Google Guava)는 일반적인 프로그래밍 작업을 간소화해주는 풍부한 유틸리티 세트를 제공하여 그 중에서도 돋보이는 라이브러리입니다.

 

구아바(Guava) 는 많은 기능을 제공하지만, 그 중 일부는 특히 놀라운 기능으로 자바 프로그래밍 경험을 크게 향상시킬 수 있습니다.

 

모든 자바 개발자가 알아야 할 10가지 구아바 기능을 소개합니다.

1. BiMap: 양방향 맵

BiMap은 키뿐만 아니라 값의 고유성도 보장하는 양방향 맵입니다. 이 양방향 맵을 사용하면 키를 값에, 값을 키에 쉽게 매핑할 수 있으며, 고유한 역 매핑을 보장합니다.

 

예제:

BiMap<String, Integer> userId = HashBiMap.create();  
userId.put("Alice", 1);  
userId.put("Bob", 2);  

System.out.println(userId.get("Alice")); // 출력: 1  
System.out.println(userId.inverse().get(2)); // 출력: Bob

2. Range: 단순 비교를 넘어서

Range 클래스는 그 표현력과 유용성 덕분에 여전히 우리의 목록에 포함되어 있습니다. 이는 Comparable 타입의 범위를 다룰 때 없어서는 안 될 도구입니다.

Range<Integer> validGrades = Range.closed(1, 100);  

System.out.println(validGrades.contains(70)); // true  
System.out.println(validGrades.contains(0));  // false

3. Table: 2차원 맵

Table 컬렉션은 아주 유용한 기능입니다. 왜냐하면, 두 개의 키를 사용하여 값을 고유하게 식별할 수 있습니다. 이를 두 개의 키를 가진 Map이라고 생각해보세요 :)

Table<String, String, Integer> universityCourseSeats = HashBasedTable.create();  
universityCourseSeats.put("Computer Science", "CS101", 30);  
universityCourseSeats.put("Mathematics", "MA101", 25);  

System.out.println(universityCourseSeats.get("Computer Science", "CS101")); // 출력: 30

4. TypeToken: 복잡한 제네릭 안전하게 다루기

자바의 제네릭은 런타임에 타입 소거로 인해 까다로워질 수 있습니다. Guava의 TypeToken 클래스는 컴파일러에 의해 소거된 후에도 제네릭 타입을 안전하게 다룰 수 있게 해줍니다. 이를 통해 동적으로 제네릭 타입에 접근하고 조작할 수 있습니다.

TypeToken<List<String>> typeToken = new TypeToken<List<String>>() {};  
Type type = typeToken.getType();  

if (type instanceof ParameterizedType) {  
    ParameterizedType pType = (ParameterizedType) type;  
    System.out.println(pType.getActualTypeArguments()[0]); // 출력: class java.lang.String  
}

5. EventBus: 이벤트 처리 간소화

Guava의 EventBus는 이벤트 생산자와 소비자를 분리하여 이벤트 관리와 처리를 간소화하는 간단하면서도 강력한 퍼블리시-구독 이벤트 시스템입니다. EventBus를 사용하면 리스너가 처리하고자 하는 이벤트 유형을 구독하고, 생산자는 이벤트를 버스에 게시하여 적절한 구독자에게 이벤트를 전달합니다.

// 이벤트 타입 정의
class CustomEvent {  
    private final String message;  

    public CustomEvent(String message) {  
        this.message = message;  
    }  

    // Getter  
    public String getMessage() {  
        return message;  
    }  
}  

// 구독자 정의
class EventListener {  
    @Subscribe  
    public void handle(CustomEvent event) {  
        System.out.println("Received event: " + event.getMessage());  
    }  
}  

// 사용 예제
EventBus eventBus = new EventBus();  
EventListener listener = new EventListener();  

// 구독자 등록
eventBus.register(listener);  

// 이벤트 게시
eventBus.post(new CustomEvent("Hello Guava EventBus!"));

6. Multimap - 하나의 키에 여러 값을 다루기

자바의 표준 Map 인터페이스는 키당 하나의 값만 허용하여 제한적일 수 있습니다.

구아바의 Multimap 인터페이스는 하나의 키에 여러 값을 연결할 수 있어, 중복이 예상되는 데이터 컬렉션을 다루기 쉽게 만듭니다.

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("Fruit", "Apple");  
        multimap.put("Fruit", "Banana");  
        multimap.put("Fruit", "Cherry");  
        multimap.put("Vegetable", "Carrot");  

        System.out.println(multimap);  
    }  
}

// 출력
// {Fruit=[Apple, Banana, Cherry], Vegetable=[Carrot]}

7. Ordering - 고급 정렬을 쉽게

자바에서 정렬은 때때로 번거로울 수 있으며, 특히 사용자 정의 정렬 로직이 필요할 때 더욱 그렇습니다.

구아바의 Ordering 클래스는 유창한 API를 제공하여 복잡한 정렬 규칙을 쉽게 만들 수 있습니다.

import com.google.common.collect.Ordering;  
import java.util.Arrays;  
import java.util.List;  

public class OrderingExample {  
    public static void main(String[] args) {  
        List<String> names = Arrays.asList("John", "Jane", "Adam", "Eve");  

        Ordering<String> byLength = Ordering.natural().onResultOf(String::length);  
        List<String> sortedNames = byLength.sortedCopy(names);  

        System.out.println(sortedNames);  
    }  
}  

// 출력
// [Eve, John, Jane, Adam]

8. CharMatcher - 문자열 조작을 쉽게

구아바의 CharMatcher 클래스는 특정 기준에 따라 문자를 다듬고, 축소하며, 제거하는 강력한 문자열 조작 유틸리티를 제공합니다.

import com.google.common.base.CharMatcher;  

public class CharMatcherExample {  
    public static void main(String[] args) {  
        String input = "   Hello, Guava!   ";  

        String result = CharMatcher.whitespace().trimAndCollapseFrom(input, ' ');  
        System.out.println(result);  // 출력: "Hello, Guava!"  

        result = CharMatcher.javaDigit().removeFrom("abc123xyz");  
        System.out.println(result);  // 출력: "abcxyz"  
    }  
}

9. Maps.uniqueIndex - 컬렉션에서 맵 생성

컬렉션에서 맵을 생성하는 것은 종종 상용구 코드를 작성하는 것을 수반합니다.

구아바의 Maps.uniqueIndex 메서드는 지정된 함수에 따라 컬렉션에서 맵을 생성하는 과정을 간소화합니다.

import com.google.common.collect.Maps;  
import java.util.List;  
import java.util.Map;  
import java.util.Arrays;  

public class UniqueIndexExample {  
    public static void main(String[] args) {  
        List<String> names = Arrays.asList("John", "Jane", "Adam", "Eve");  

        Map<Character, String> nameMap = Maps.uniqueIndex(names, name -> name.charAt(0));  

        System.out.println(nameMap);  
    }  
}  
// 출력: {J=John, J=Jane, A=Adam, E=Eve}

10. Lists.partition - 리스트를 서브리스트로 나누기

큰 리스트를 다루는 것은 특히 그것을 청크 단위로 처리해야 할 때 어려울 수 있습니다.

구아바의 Lists.partition 메서드는 리스트를 더 작은 서브리스트로 나누어 큰 데이터셋을 관리하고 처리하기 쉽게 만듭니다.

import com.google.common.collect.Lists;  
import java.util.List;  
import java.util.Arrays;  

public class PartitionExample {  
    public static void main(String[] args) {  
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);  

        List<List<Integer>> partitions = Lists.partition(numbers, 3);  

        for (List<Integer> partition : partitions) {  
            System.out.println(partition);  
        }  
    }  
}  

// 출력
// [1, 2, 3]
// [4, 5, 6]
// [7, 8, 9]

 

구아바는 자바 개발자들에게 복잡한 작업을 단순화하고 코드 가독성을 향상시키는 다양한 유틸리티를 제공하는 귀중한 도구로 계속 자리매김하고 있습니다. 이 기능들을 프로젝트에 통합함으로써 더 깔끔하고 효율적이며 유지보수가 용이한 코드를 작성하세요 ! :) 

 

🙏 끝까지 읽어주셔서 감사합니다.

좋은 하루 되세요 !!