[java] Guava:Google Core Libraries 활용법, 예제 코드

nana·2024년 10월 18일
1

JAVA

목록 보기
7/11

Initialize

Google의 유용한 라이브러리인 Guava의 활용법을 알아보자.

https://mvnrepository.com/artifact/com.google.guava/guava/11.0.2

  • Objects.equal() : equal비교시 null체크 하지 않아도 된다.
 @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book book = (Book) o;
        return Objects.equal(this.title, book.title) && Objects.equal(this.writer, book.writer)
                && this.price == book.price;

    }
  • Objects.hashCode() : hash코드 생성을 보다 쉽게 만들 수 있다.
 @Override
    public int hashCode() {
        return Objects.hashCode(this.title, this.writer, this.price);
    }
  • Objects.toStringHelper() : toString 객체를 보다 쉽게 만들 수 있다.
@Override
    public String toString() {
        return Objects.toStringHelper(this)
                .add("title", title)
                .add("writer", writer)
                .add("price", price)
                .toString();
    }
  • Preconditions : 객체 정보의 null과 같은 정보가 있는지 미리 확인하여 exception을 낸다.
    public void setTitle(String title) {
      Preconditions.checkNotNull(title);
      this.title = title;
    }
  • Joiner : Collections객체들이나 array객체들의 정보를 string으로 변경해준다.
    List names = new ArrayList<>();
    names.add("test1");
    names.add("test2");
    names.add("test3");

Joiner.on(", ").join(names); // test1, test2, test3

* <code>Splitter</code> : Joiner와 반대로 split캐릭터를 기준으로 Iterator객체로 변환하여 준다. 

* <code>Collections</code> : List, Set, Map을 보통 new를 통해 생성하는데 Guava에서는 static facotry생성자를 이용한다. 
``` java 
Lists.newArrayList();
Sets.newHashSet();
Maps.newHashMap();
  • Immutable : 변경 불가능한 Collection. 객체들에 대한 의도하지 않은 변경을 막고 Thread-Safe한 객체를 만들 수 있다.
    Map<String, Integer> mapValue1 = new LinkedHashMap<>();
    mapValue1.put("test1", 1);
    mapValue1.put("test2", 2);
    mapValue1.put("test3", 3);
    Map<String, Integer> unModifiedMap = Collections.unmodifiableMap(mapValue1);

Map<String, Integer> mapValue2 = ImmutableMap.<String, Integer>builder()
.put("test1", 1).put("test2", 2).put("test3", 3)
.build();

Map<String, Integer> mapValue3 = ImmutableMap.of("test1", 1, "test2", 2, "test3", 3);

## Gradle 
```java 
//https://mvnrepository.com/artifact/com.google.guava/guava
implementation 'com.google.guava:guava:11.0.2'

Maven

***

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>11.0.2</version>
</dependency>

참고
https://drcarter.tistory.com/171

profile
BackEnd Developer, 기록의 힘을 믿습니다.

0개의 댓글