Google Guavaは、Googleが開発したJavaプログラミング言語向けのオープンソースのユーティリティライブラリです。Guavaは、Java標準ライブラリには含まれていない便利な機能やデータ構造、ユーティリティメソッドを提供します。

Wikipedia
Wikipedia
ウィキペディアGoogle Guavaの記事があります。

Guavaは、コーディングの効率性と品質を向上させるために設計されています。これには、コレクションフレームワークの強化、関数型プログラミングスタイルのサポート、文字列操作やI/O操作などの機能が含まれます。また、Guavaは安定しており、幅広いユーザーによって使用されています。

主な機能には、Immutable Collections(イミュータブルなコレクション)、Functional Programming Utilities(関数型プログラミングユーティリティ)、Caches(キャッシュ)、Strings Utilities(文字列ユーティリティ)、Concurrency Utilities(並行性ユーティリティ)などがあります。これらの機能は、Javaプログラマーがコードをより効率的に記述し、より堅牢なアプリケーションを構築するのに役立ちます。

特徴 編集

Google Guavaの特徴は次のとおりです: 豊富な機能セット: Guavaは、Javaの標準ライブラリにはない便利な機能を提供します。 これには、コレクション、文字列、I/O、並行性など、さまざまな領域でのユーティリティメソッドやデータ構造が含まれます。

  1. イミュータブルなコレクション: Guavaは、イミュータブルなコレクションを提供し、変更不能なデータ構造を使うことで安全性を向上させます。これにより、意図しない変更や競合状態を回避するのに役立ちます。
  2. 関数型プログラミングのサポート: Guavaは、関数型プログラミングのスタイルをサポートし、関数型インターフェースや関数型プログラミングパターンを提供します。これにより、コードの明確さや再利用性が向上し、エラーの可能性が減ります。
  3. 高性能なキャッシュ: Guavaのキャッシュ機能は、アプリケーションのパフォーマンスを向上させるのに役立ちます。キャッシュされたデータへのアクセス速度を高め、外部リソースへの負荷を減らします。
  4. コードの効率化: Guavaは、コードの効率性を向上させるためのユーティリティやベストプラクティスを提供します。これにより、より効率的でメンテナンス性の高いコードを書くことができます。
  5. 広範なコミュニティとサポート: Guavaは、Googleを含む広範なコミュニティによってサポートされており、定期的な更新やバグ修正が行われています。これにより、安定性や信頼性が確保されます。

クイックツアー 編集

  1. 関数型プログラミングのサポート:
    Guavaは、関数型プログラミングスタイルをサポートしており、関数型インターフェースや関数合成などの機能を提供します。
    Function<Integer, String> intToString = Object::toString;
    List<String> stringList = Lists.transform(ImmutableList.of(1, 2, 3), intToString);
    
  2. キャッシュの利用:
    Guavaのキャッシュ機能は、アプリケーションのパフォーマンスを向上させるのに役立ちます。キャッシュされたデータへのアクセス速度を高め、外部リソースへの負荷を減らします。
    LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .build(
                new CacheLoader<Key, Graph>() {
                  public Graph load(Key key) throws AnyException {
                    return createExpensiveGraph(key);
                  }
                });
    
  3. 文字列処理:
    Guavaは、文字列操作を行うための便利なユーティリティメソッドを提供します。
    String input = "foo , bar , baz";
    Iterable<String> parts = Splitter.on(',')
                                    .trimResults()
                                    .omitEmptyStrings()
                                    .split(input);
    
  4. イミュータブルなコレクション:
    Guavaのイミュータブルなコレクションは、変更不可能なデータ構造を提供します。これにより、データの安全性が向上し、意図しない変更や競合状態を回避することができます。
    ImmutableList<String> immutableList = ImmutableList.of("apple", "banana", "orange");
    ImmutableMap<Integer, String> immutableMap = ImmutableMap.of(1, "one", 2, "two");
    
  5. イミュータブルなコレクション操作:
    Guavaは、イミュータブルなコレクションを操作するための便利なメソッドを提供します。
    ImmutableList<String> originalList = ImmutableList.of("apple", "banana", "orange");
    ImmutableList<String> newList = ImmutableList.<String>builder()
                                            .addAll(originalList)
                                            .add("grape")
                                            .build();
    
  6. Java標準ライブラリの拡張:
    Guavaは、Java標準ライブラリを補完し、さまざまな領域で機能を拡張します。これには、Javaの古いバージョンでは利用できない新しい機能のサポートや、より使いやすいAPIの提供が含まれます。
  7. コンカレンシーの管理:
    Guavaは、並行性を扱うための機能を提供します。これには、スレッドセーフなコレクションや同期ユーティリティなどが含まれます。これにより、複数のスレッドからのアクセスを安全に行うことができます。
  8. 便利なユーティリティメソッド:
    Guavaには、様々な便利なユーティリティメソッドが含まれています。これにより、より効率的かつ読みやすいコードを書くことができます。例えば、GuavaのPreconditionsクラスは、事前条件をチェックするための便利なメソッドを提供します。
    import com.google.common.base.Preconditions;
    
    public class MyClass {
        private String data;
    
        public MyClass(String data) {
            this.data = Preconditions.checkNotNull(data, "Data must not be null");
        }
    }
    

これらの例は、Google Guavaの一部機能の使用方法を示していますが、Guavaにはさらに多くの便利な機能があります。

Guavaと重複するJava SEの機能 編集

Google Guavaは、Java SEの標準ライブラリには含まれていない、いくつかの便利な機能や拡張を提供しますが、一部の機能はJava SEの標準ライブラリでも利用可能です。以下は、Guavaと重複するJava SEの機能の例です:

  1. コレクションフレームワーク: Java SEには、java.utilパッケージに含まれるコレクションフレームワークがあります。これには、ArrayListHashMapHashSetなどのデータ構造が含まれます。Guavaのコレクションはこれらのクラスを補完するものであり、不変のコレクションや便利なメソッドを提供します。
  2. 文字列操作: Java SEには、java.lang.Stringクラスに多くの文字列操作メソッドが含まれています。これには、substring()split()trim()などが含まれます。Guavaはこれらの機能を補完するものであり、より高度な文字列操作や便利なユーティリティを提供します。
  3. 並行性ユーティリティ: Java SEには、java.util.concurrentパッケージに多くの並行性関連のユーティリティが含まれています。これには、ExecutorConcurrentHashMapSemaphoreなどが含まれます。Guavaも並行性ユーティリティを提供しますが、Java SEの機能と同等のものが多く存在します。
  4. 例外処理: Java SEには、例外処理のための標準的な仕組みがあります。これには、try-catchブロックやthrowsキーワードなどが含まれます。GuavaのThrowablesクラスは、例外処理に関連する便利なユーティリティメソッドを提供しますが、Java SEの機能と比較すると、補完的なものです。

Java SEの標準ライブラリには多くの便利な機能が含まれていますが、Guavaはそれらを補完し、より効率的なコーディングやより堅牢なアプリケーションを構築するための追加機能を提供します。

機能分類 編集

Google Guavaの機能は主に以下のカテゴリに分類されます:

  1. com.google.common.annotations: アノテーションの種類を提供します。
    import com.google.common.annotations.Beta;
    
    public class Main {
        @Beta
        public void someMethod() {
            // ベータ版APIを使用する例
        }
    }
    
  2. com.google.common.base: 基本的なユーティリティライブラリやインターフェースを提供します。
    import com.google.common.base.Joiner;
    
    public class Main {
        public static void main(String[] args) {
            String joinedString = Joiner.on(", ").join("apple", "banana", "orange");
            System.out.println(joinedString);
        }
    }
    
  3. com.google.common.cache: キャッシュ関連のユーティリティが含まれています。ただし、Caffeineが推奨されることになりました。
    import com.google.common.cache.Cache;
    import com.google.common.cache.CacheBuilder;
    
    public class Main {
        public static void main(String[] args) {
            Cache<String, Integer> cache = CacheBuilder.newBuilder().build();
            cache.put("key", 123);
            int value = cache.getIfPresent("key");
            System.out.println(value);
        }
    }
    
  4. com.google.common.collect: コレクションのインターフェースや実装、その他のコレクション用のユーティリティを提供します。
    import com.google.common.collect.ImmutableList;
    
    public class Main {
        public static void main(String[] args) {
            ImmutableList<String> list = ImmutableList.of("apple", "banana", "orange");
            System.out.println(list);
        }
    }
    
  5. com.google.common.escape: エスケーパーやエンコーダーのインターフェース、ユーティリティ、およびシンプルな実装を提供します。
    import com.google.common.escape.Escaper;
    import com.google.common.html.HtmlEscapers;
    
    public class Main {
        public static void main(String[] args) {
            Escaper escaper = HtmlEscapers.htmlEscaper();
            String html = "<script>alert('XSS');</script>";
            String escapedHtml = escaper.escape(html);
            System.out.println(escapedHtml);
        }
    }
    
  6. com.google.common.eventbus: EventBusは、依存関係の注入や並行性フレームワークを推奨されますが、これは発行-購読スタイルの通信を可能にします。
    import com.google.common.eventbus.EventBus;
    import com.google.common.eventbus.Subscribe;
    
    public class Main {
        public static void main(String[] args) {
            EventBus eventBus = new EventBus();
            eventBus.register(new EventListener());
            eventBus.post("Hello, world!");
        }
    
        static class EventListener {
            @Subscribe
            public void handleEvent(String event) {
                System.out.println("Received event: " + event);
            }
        }
    }
    
  7. com.google.common.graph: グラフ(ノードとエッジ)データを表現するためのAPIが含まれます。
    import com.google.common.graph.Graph;
    import com.google.common.graph.ImmutableGraph;
    import com.google.common.graph.GraphBuilder;
    
    public class Main {
        public static void main(String[] args) {
            Graph<Integer> graph = GraphBuilder.undirected().build();
            graph.addNode(1);
            graph.addNode(2);
            graph.putEdge(1, 2);
    
            System.out.println(graph.hasEdgeConnecting(1, 2));
        }
    }
    
  8. com.google.common.hash: ハッシュ関数や関連構造を提供します。
    import com.google.common.hash.HashFunction;
    import com.google.common.hash.Hashing;
    
    public class Main {
        public static void main(String[] args) {
            HashFunction hashFunction = Hashing.sha256();
            String input = "Hello, world!";
            String hashed = hashFunction.hashBytes(input.getBytes()).toString();
            System.out.println("Hashed value: " + hashed);
        }
    }
    
  9. com.google.common.html: HTML用のエスケーパーが含まれています。
    import com.google.common.html.HtmlEscapers;
    
    public class Main {
        public static void main(String[] args) {
            String unsafeHtml = "<script>alert('XSS');</script>";
            String safeHtml = HtmlEscapers.htmlEscaper().escape(unsafeHtml);
            System.out.println("Safe HTML: " + safeHtml);
        }
    }
    
  10. com.google.common.io: 入力ストリーム、出力ストリーム、リーダー、ライター、ファイルなどのI/Oに関するユーティリティメソッドとクラスが含まれています。
    import com.google.common.io.Files;
    
    import java.io.File;
    import java.io.IOException;
    import java.nio.charset.StandardCharsets;
    
    public class Main {
        public static void main(String[] args) throws IOException {
            File file = new File("example.txt");
            Files.write("Hello, world!", file, StandardCharsets.UTF_8);
            String content = Files.asCharSource(file, StandardCharsets.UTF_8).read();
            System.out.println("File content: " + content);
        }
    }
    
  11. com.google.common.math: プリミティブ値やBigInteger、BigDecimalインスタンスに対して動作する算術関数が含まれています。
    import com.google.common.math.BigIntegerMath;
    
    import java.math.BigInteger;
    import java.math.RoundingMode;
    
    public class Main {
        public static void main(String[] args) {
            BigInteger factorial = BigIntegerMath.factorial(5);
            System.out.println("Factorial of 5: " + factorial);
            double sqrtTwo = BigIntegerMath.sqrt(BigInteger.valueOf(2), RoundingMode.HALF_EVEN).doubleValue();
            System.out.println("Square root of 2: " + sqrtTwo);
        }
    }
    
  12. com.google.common.net: ネットワーキングに関するユーティリティメソッドやクラスが含まれています(IPアドレスやドメイン名など)。
    import com.google.common.net.InetAddresses;
    
    import java.net.InetAddress;
    
    public class Main {
        public static void main(String[] args) {
            String ipAddress = "192.168.1.1";
            InetAddress inetAddress = InetAddresses.forString(ipAddress);
            System.out.println("IP Address: " + inetAddress);
            boolean isIpv4 = InetAddresses.isInetAddress(ipAddress);
            System.out.println("Is IPv4 address: " + isIpv4);
        }
    }
    
  13. com.google.common.primitives: 8つのプリミティブ型とvoidのための静的ユーティリティや、これらを符号なしとして扱ったり、不変の配列に格納したりするための値型が含まれています。
    import com.google.common.primitives.Ints;
    
    public class Main {
        public static void main(String[] args) {
            int[] numbers = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
            int min = Ints.min(numbers);
            int max = Ints.max(numbers);
            System.out.println("Minimum: " + min);
            System.out.println("Maximum: " + max);
        }
    }
    
  14. com.google.common.reflect: リフレクションに関するユーティリティが含まれています。
    import com.google.common.reflect.TypeToken;
    
    import java.util.List;
    
    public class Main {
        public static void main(String[] args) {
            TypeToken<List<String>> typeToken = new TypeToken<List<String>>() {};
            System.out.println("Type: " + typeToken.getType());
        }
    }
    
  15. com.google.common.util.concurrent: 並行性に関するユーティリティが含まれています。
    import com.google.common.util.concurrent.ListeningExecutorService;
    import com.google.common.util.concurrent.MoreExecutors;
    import com.google.common.util.concurrent.ThreadFactoryBuilder;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    
    public class Main {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            // スレッドプールを作成
            ListeningExecutorService executorService = MoreExecutors.listeningDecorator(
                    Executors.newFixedThreadPool(2, new ThreadFactoryBuilder().setNameFormat("worker-%d").build()));
    
            // タスクの実行
            executorService.submit(() -> {
                System.out.println("Task 1 is running...");
                return "Task 1";
            });
    
            executorService.submit(() -> {
                System.out.println("Task 2 is running...");
                return "Task 2";
            });
    
            // シャットダウン
            executorService.shutdown();
            executorService.awaitTermination(10, TimeUnit.SECONDS);
        }
    }
    
  16. com.google.common.xml: XML用のエスケーパーが含まれています。
    import com.google.common.xml.XmlEscapers;
    
    public class Main {
        public static void main(String[] args) {
            String unsafeXml = "<message>Hello, world!</message>";
            String safeXml = XmlEscapers.xmlContentEscaper().escape(unsafeXml);
            System.out.println("Safe XML: " + safeXml);
        }
    }
    

これらのパッケージは、Google Guavaが提供する機能を効果的に組織化しており、開発者が必要な機能を見つけやすくなっています。

リソース 編集

Google Guavaに関するリソースは以下の通りです:

  1. Google Guavaの公式ウェブサイト
    https://guava.dev/
    ドキュメント、APIリファレンス、最新のリリース情報などを提供しています。
  2. GitHubリポジトリ
    https://github.com/google/guava
    Google Guavaのソースコードや最新の開発情報は、GitHubリポジトリで入手できます。また、問題の追跡やプロジェクトへの貢献もここで行われます。
  3. Google Guava Wiki
    https://github.com/google/guava/wiki
    Google GuavaのWikiでは、より詳細なドキュメントや使用例、パフォーマンスガイド、FAQなどが提供されています。