### Build and Install Guava Source: https://github.com/google/guava/blob/master/CONTRIBUTING.md Use this command to clean, build, and install Guava using the Maven wrapper. ```shell ./mvnw clean install ``` -------------------------------- ### Basic Hashing Example Source: https://github.com/google/guava/wiki/HashingExplained Demonstrates creating a HashFunction, using a Hasher to add various data types, and hashing the result. Requires a Funnel for custom objects. ```java HashFunction hf = Hashing.md5(); HashCode hc = hf.newHasher() .putLong(id) .putString(name, UTF_8) .putObject(person, personFunnel) .hash(); ``` -------------------------------- ### BiMap Inverse and Force Put Example Source: https://github.com/google/guava/wiki/NewCollectionTypesExplained Demonstrates how to use the inverse view of a BiMap to retrieve a key by its value and how to use forcePut to overwrite an existing mapping. ```java Map nameToId = Maps.newHashMap(); Map idToName = Maps.newHashMap(); nameToId.put("Bob", 42); idToName.put(42, "Bob"); // what happens if "Bob" or 42 are already present? // weird bugs can arise if we forget to keep these in sync... BiMap userId = HashBiMap.create(); ... String userForId = userId.inverse().get(id); ``` -------------------------------- ### Implement startUp, run, and triggerShutdown for AbstractExecutionThreadService Source: https://github.com/google/guava/wiki/ServiceExplained This example demonstrates a more complete implementation of AbstractExecutionThreadService, including startUp for setting up listeners, run for processing work items from a queue, and triggerShutdown for stopping the listener and signaling the run loop to exit. ```java protected void startUp() { dispatcher.listenForConnections(port, queue); } protected void run() { Connection connection; while ((connection = queue.take() != POISON)) { process(connection); } } protected void triggerShutdown() { dispatcher.stopListeningForConnections(queue); queue.put(POISON); } ``` -------------------------------- ### Confusing exception handling with Throwables.propagate Source: https://github.com/google/guava/wiki/Why-we-deprecated-Throwables.propagate This example demonstrates how Throwables.propagate can obscure the actual exception being handled, leading to misinterpretation. ```java try { return callable.call(); } catch (AssertionError e) { int delay = retryStrategy.getDelayMillis(tries); if (delay >= 0) { try { Thread.sleep(delay); } catch (InterruptedException ie) { throw Throwables.propagate(e); } } } ``` -------------------------------- ### RangeMap Operations Example Source: https://github.com/google/guava/wiki/NewCollectionTypesExplained Demonstrates basic put, remove, and implicit splitting operations on a TreeRangeMap. Adjacent ranges are not coalesced. ```java RangeMap rangeMap = TreeRangeMap.create(); rangeMap.put(Range.closed(1, 10), "foo"); // {[1, 10] => "foo"} rangeMap.put(Range.open(3, 6), "bar"); // {[1, 3] => "foo", (3, 6) => "bar", [6, 10] => "foo"} rangeMap.put(Range.open(10, 20), "foo"); // {[1, 3] => "foo", (3, 6) => "bar", [6, 10] => "foo", (10, 20) => "foo"} rangeMap.remove(Range.closed(5, 11)); // {[1, 3] => "foo", (3, 5) => "bar", (11, 20) => "foo"} ``` -------------------------------- ### Guava Function and Predicate Example Source: https://github.com/google/guava/wiki/FunctionalExplained Demonstrates the use of Guava's Function and Predicate interfaces for transforming and filtering collections. This approach can be less concise and readable than imperative code. ```java Function lengthFunction = new Function() { public Integer apply(String string) { return string.length(); } }; Predicate allCaps = new Predicate() { public boolean apply(String string) { return CharMatcher.javaUpperCase().matchesAllOf(string); } }; Multiset lengths = HashMultiset.create( Iterables.transform(Iterables.filter(strings, allCaps), lengthFunction)); ``` ```java Multiset lengths = HashMultiset.create( FluentIterable.from(strings) .filter(new Predicate() { public boolean apply(String string) { return CharMatcher.javaUpperCase().matchesAllOf(string); } }) .transform(new Function() { public Integer apply(String string) { return string.length(); } })); ``` -------------------------------- ### Guava Static Constructors with Initial Elements Source: https://github.com/google/guava/wiki/CollectionUtilitiesExplained Initialize collections with their starting elements in a single line using Guava's static factory methods. For immutable collections, consider Guava's immutable collection types. ```java Set copySet = Sets.newHashSet(elements); List theseElements = Lists.newArrayList("alpha", "beta", "gamma"); ``` -------------------------------- ### Cache with Maximum Weight and Custom Weigher Source: https://github.com/google/guava/wiki/CachesExplained Use maximumWeight and weigher to control cache size based on entry weights. Weights are computed at creation time and are static thereafter. This example uses the number of vertices in a graph as its weight. ```java LoadingCache graphs = CacheBuilder.newBuilder() .maximumWeight(100000) .weigher(new Weigher() { public int weigh(Key k, Graph g) { return g.vertices().size(); } }) .build( new CacheLoader() { public Graph load(Key key) { // no checked exception return createExpensiveGraph(key); } }); ``` -------------------------------- ### Invert Multimap with Custom Implementation Source: https://github.com/google/guava/wiki/CollectionUtilitiesExplained Inverts a Multimap, allowing you to specify the implementation for the resulting inverse Multimap. Useful when the default implementation is not suitable. The example demonstrates inverting an ArrayListMultimap into a TreeMultimap to get ordered results. ```java ArrayListMultimap multimap = ArrayListMultimap.create(); multimap.putAll("b", Ints.asList(2, 4, 6)); multimap.putAll("a", Ints.asList(4, 2, 1)); multimap.putAll("c", Ints.asList(2, 5, 3)); TreeMultimap inverse = Multimaps.invertFrom(multimap, TreeMultimap.create()); // note that we choose the implementation, so if we use a TreeMultimap, we get results in order /* * inverse maps: * 1 => {"a"} * 2 => {"a", "b", "c"} * 3 => {"c"} * 4 => {"a", "b"} * 5 => {"c"} * 6 => {"b"} */ ``` -------------------------------- ### Get Return Type with Invokable Source: https://github.com/google/guava/wiki/ReflectionExplained Invokable simplifies getting the return type of a method, including type resolution. ```java Invokable, ?> invokable = new TypeToken>() {}.method(getMethod); invokable.getReturnType(); // String.class ``` -------------------------------- ### Create a LoadingCache with Guava Source: https://github.com/google/guava/wiki/CachesExplained Demonstrates how to build a LoadingCache with specific configurations like maximum size, expiration, and a removal listener. Use this when values are expensive to compute and need to be loaded automatically. ```java LoadingCache graphs = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(10, TimeUnit.MINUTES) .removalListener(MY_LISTENER) .build( new CacheLoader() { @Override public Graph load(Key key) throws AnyException { return createExpensiveGraph(key); } }); ``` -------------------------------- ### Get Registry Suffix of Domain Source: https://github.com/google/guava/wiki/InternetDomainNameExplained Use `topDomainUnderRegistrySuffix()` to get the domain name purchased from a registry, which differs from the public suffix. ```java InternetDomainName owner = InternetDomainName.from("foo.blogspot.com").topDomainUnderRegistrySuffix(); ``` -------------------------------- ### Implement startUp and shutDown for AbstractIdleService Source: https://github.com/google/guava/wiki/ServiceExplained Extend AbstractIdleService and implement startUp() and shutDown() for services that do not require a dedicated thread while running. This is suitable for services with only startup and shutdown actions. ```java protected void startUp() { servlets.add(new GcStatsServlet()); } protected void shutDown() {} ``` -------------------------------- ### Get Bytes using StandardCharsets Source: https://github.com/google/guava/wiki/StringsExplained Replaces the older, exception-prone method of getting bytes with UTF-8 encoding. Requires importing UTF_8 from java.nio.charset.StandardCharsets. ```java try { bytes = string.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { // how can this possibly happen? throw new AssertionError(e); } ``` ```java bytes = string.getBytes(UTF_8); ``` -------------------------------- ### Traverse Undirected Graph Node-wise in Guava Source: https://github.com/google/guava/wiki/GraphsExplained Finds all nodes reachable by traversing exactly two edges from a starting node in an undirected graph, excluding the starting node itself. ```java // Return all nodes reachable by traversing 2 edges starting from "node" // (ignoring edge direction and edge weights, if any, and not including "node"). Set getTwoHopNeighbors(Graph graph, N node) { Set twoHopNeighbors = new HashSet<>(); for (N neighbor : graph.adjacentNodes(node)) { twoHopNeighbors.addAll(graph.adjacentNodes(neighbor)); } twoHopNeighbors.remove(node); return twoHopNeighbors; } ``` -------------------------------- ### Check Position Indexes Source: https://github.com/google/guava/wiki/PreconditionsExplained Verifies that both start and end indices are within the valid range [0, size] and that end is not less than start. Throws IndexOutOfBoundsException if the indices are invalid. ```java checkPositionIndexes(int start, int end, int size); ``` -------------------------------- ### Creating Ranges with Static Methods in Java Source: https://github.com/google/guava/wiki/RangesExplained Shows how to create different types of ranges using static factory methods in Guava. ```java Range.closed("left", "right"); // all strings lexographically between "left" and "right" inclusive Range.lessThan(4.0); // double values strictly less than 4 ``` -------------------------------- ### Guava Static Constructors with Capacity Hints Source: https://github.com/google/guava/wiki/CollectionUtilitiesExplained Initialize collections with a specified capacity or expected size to optimize performance. Use `newArrayListWithCapacity` for exact capacity or `newArrayListWithExpectedSize` for an estimated size. ```java List exactly100 = Lists.newArrayListWithCapacity(100); List approx100 = Lists.newArrayListWithExpectedSize(100); Set approx100Set = Sets.newHashSetWithExpectedSize(100); ``` -------------------------------- ### Task Partitioning (Before CountingIterator) Source: https://github.com/google/guava/wiki/IdeaGraveyard Illustrates a manual implementation of task batching using CountingIterator, which was later replaced by a more direct 'partition' utility. ```java CountingIterator iter = CountingIterator.from(tasks); while (iter.hasNext()) { List batch = Lists.newArrayList(); do { batch.add(iter.next()); } while (iter.hasNext() && (iter.getCount() % TASKS_PER_BATCH) > 0); // Plus, the above test could have used batch.size() and // not needed CountingIterator. ``` ```java for (List batch : partition(tasks, TASKS_PER_BATCH)) { ``` -------------------------------- ### Reverse and Partition a List using Guava Source: https://github.com/google/guava/wiki/CollectionUtilitiesExplained Demonstrates reversing a list and partitioning it into sublists of a specified size using Guava's Lists utility class. ```java List countUp = Ints.asList(1, 2, 3, 4, 5); List countDown = Lists.reverse(theList); // {5, 4, 3, 2, 1} List> parts = Lists.partition(countUp, 2); // {{1, 2}, {3, 4}, {5}} ``` -------------------------------- ### Obtain TypeToken for a Raw Class Source: https://github.com/google/guava/wiki/ReflectionExplained Demonstrates the basic usage of TypeToken.of() to get a TypeToken for a simple, non-generic class like String or Integer. ```java TypeToken stringTok = TypeToken.of(String.class); TypeToken intTok = TypeToken.of(Integer.class); ``` -------------------------------- ### Create and Use ListenableFuture with Callbacks Source: https://github.com/google/guava/wiki/ListenableFutureExplained Demonstrates creating a ListeningExecutorService, submitting a task that returns a ListenableFuture, and attaching a FutureCallback to handle success or failure. The callback is executed on the provided executor. ```java ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); ListenableFuture explosion = service.submit( new Callable() { public Explosion call() { return pushBigRedButton(); } }); Futures.addCallback( explosion, new FutureCallback() { // we want this handler to run immediately after we push the big red button! public void onSuccess(Explosion explosion) { walkAwayFrom(explosion); } public void onFailure(Throwable thrown) { battleArchNemesis(); // escaped the explosion! } }, service); ``` -------------------------------- ### Imperative Code Equivalent Source: https://github.com/google/guava/wiki/FunctionalExplained An imperative approach to achieve the same result as the functional example, often proving more concise, readable, and efficient. This should be the default choice. ```java Multiset lengths = HashMultiset.create(); for (String string : strings) { if (CharMatcher.javaUpperCase().matchesAllOf(string)) { lengths.add(string.length()); } } ``` -------------------------------- ### Building Ranges with Explicit Bounds in Java Source: https://github.com/google/guava/wiki/RangesExplained Illustrates constructing ranges by explicitly specifying endpoints and their bound types (CLOSED or OPEN). ```java Range.downTo(4, boundType); // allows you to decide whether or not you want to include 4 Range.range(1, CLOSED, 4, OPEN); // another way of writing Range.closedOpen(1, 4) ``` -------------------------------- ### Verify Ordering with Reversed Ordering Source: https://github.com/google/guava/wiki/OrderingExplained Demonstrates how to use a reversed Ordering to check if a list is ordered. ```java assertTrue(byLengthOrdering.reverse().isOrdered(list)); ``` -------------------------------- ### Find Linear Approximation (Least Squares Fit) Source: https://github.com/google/guava/wiki/StatsExplained Determine a linear approximation for ordered pairs using `PairedStatsAccumulator.leastSquaresFit()`. This provides methods to get the slope, y-intercept, and perform transformations. ```java PairedStatsAccumulator accum = new PairedStatsAccumulator(); for (...) { ... accum.add(x, y); } LinearTransformation bestFit = accum.leastSquaresFit(); double slope = bestFit.slope(); double yIntercept = bestFit.transform(0); double estimateXWhenYEquals5 = bestFit.inverse().transform(5); ``` -------------------------------- ### Registering and Posting Events with EventBus Source: https://github.com/google/guava/wiki/EventBusExplained Demonstrates how to register a subscriber class with EventBus and how to post an event. Ensure the subscriber class is registered before posting events to avoid them being dropped. ```java class EventBusChangeRecorder { @Subscribe public void recordCustomerChange(ChangeEvent e) { recordChange(e.getChange()); } } // somewhere during initialization eventBus.register(new EventBusChangeRecorder()); // much later public void changeCustomer() ChangeEvent event = getChangeEvent(); eventBus.post(event); } ``` -------------------------------- ### Get Top Private Domain of an Internet Domain Name Source: https://github.com/google/guava/wiki/InternetDomainNameExplained Extracts the 'top private domain' from a given InternetDomainName. This is often used to identify the 'owner' domain, such as 'google.com' from 'mail.google.com'. ```java InternetDomainName owner = InternetDomainName.from("mail.google.com").topPrivateDomain(); ``` -------------------------------- ### Configure Cache with Removal Listener Source: https://github.com/google/guava/wiki/CachesExplained Sets up a cache with expiration and a removal listener to close database connections when entries are removed. Exceptions from the listener are logged and swallowed. ```java CacheLoader loader = new CacheLoader () { public DatabaseConnection load(Key key) throws Exception { return openConnection(key); } }; RemovalListener removalListener = new RemovalListener() { public void onRemoval(RemovalNotification removal) { DatabaseConnection conn = removal.getValue(); conn.close(); // tear down properly } }; return CacheBuilder.newBuilder() .expireAfterWrite(2, TimeUnit.MINUTES) .removalListener(removalListener) .build(loader); ``` -------------------------------- ### Chaining Asynchronous Operations with ListenableFuture Source: https://github.com/google/guava/wiki/ListenableFutureExplained Use this pattern to chain asynchronous operations where the result of one future is used to start another. Requires Guava's Futures and an Executor. ```java ListenableFuture rowKeyFuture = indexService.lookUp(query); AsyncFunction queryFunction = new AsyncFunction() { public ListenableFuture apply(RowKey rowKey) { return dataService.read(rowKey); } }; ListenableFuture queryFuture = Futures.transformAsync(rowKeyFuture, queryFunction, queryExecutor); ``` -------------------------------- ### Create CacheLoader from Function Source: https://github.com/google/guava/wiki/MapMakerMigration Use CacheLoader.from(Function) as a simple adapter to migrate Function-based computing maps to CacheLoader. ```java new CacheLoader() { public V load(K key) { // copy/paste code from Function.apply } } ``` -------------------------------- ### Create ImmutableSet with `builder` Source: https://github.com/google/guava/wiki/ImmutableCollectionsExplained Shows how to create an ImmutableSet using a builder, adding elements from another collection and individual elements. ```java public static final ImmutableSet GOOGLE_COLORS = ImmutableSet.builder() .addAll(WEBSAFE_COLORS) .add(new Color(0, 191, 255)) .build(); ``` -------------------------------- ### Dynamically Resolve Generic Type Arguments with TypeToken Source: https://github.com/google/guava/wiki/ReflectionExplained This example demonstrates how to dynamically resolve generic type arguments for a Map using a helper method and TypeToken's where() method. ```java static TypeToken> mapToken(TypeToken keyToken, TypeToken valueToken) { return new TypeToken>() {} .where(new TypeParameter() {}, keyToken) .where(new TypeParameter() {}, valueToken); } ... TypeToken> mapToken = mapToken( TypeToken.of(String.class), TypeToken.of(BigInteger.class)); TypeToken>> complexToken = mapToken( TypeToken.of(Integer.class), new TypeToken>() {}); ``` -------------------------------- ### Demonstrate Type Erasure with ArrayList Source: https://github.com/google/guava/wiki/ReflectionExplained This example shows how Java's type erasure makes ArrayList and ArrayList appear the same at runtime using getClass().isAssignableFrom(). ```java ArrayList stringList = Lists.newArrayList(); ArrayList intList = Lists.newArrayList(); System.out.println(stringList.getClass().isAssignableFrom(intList.getClass())); // returns true, even though ArrayList is not assignable from ArrayList ``` -------------------------------- ### Basic Math Functions in Guava Source: https://github.com/google/guava/wiki/MathExplained Demonstrates the usage of various basic math functions from Guava's math utility classes for different numeric types and rounding modes. ```java int logFloor = LongMath.log2(n, FLOOR); int mustNotOverflow = IntMath.checkedMultiply(x, y); long quotient = LongMath.divide(knownMultipleOfThree, 3, RoundingMode.UNNECESSARY); // fail fast on non-multiple of 3 BigInteger nearestInteger = DoubleMath.roundToBigInteger(d, RoundingMode.HALF_EVEN); BigInteger sideLength = BigIntegerMath.sqrt(area, CEILING); ``` -------------------------------- ### Set Creation Utilities Source: https://github.com/google/guava/wiki/CollectionUtilitiesExplained Utilities for creating different types of Sets. ```APIDOC ## Sets ### newHashSet() Creates an empty HashSet. ### newHashSet(E...) Creates a HashSet containing the given elements. ### newHashSet(Iterable) Creates a HashSet containing the elements from the given Iterable. ### newHashSetWithExpectedSize(int) Creates an empty HashSet with the specified initial capacity. ### newHashSet(Iterator) Creates a HashSet containing the elements from the given Iterator. ### newLinkedHashSet() Creates an empty LinkedHashSet. ### newLinkedHashSet(Iterable) Creates a LinkedHashSet containing the elements from the given Iterable. ### newLinkedHashSetWithExpectedSize(int) Creates an empty LinkedHashSet with the specified initial capacity. ### newTreeSet() Creates an empty TreeSet. ### newTreeSet(Comparator) Creates an empty TreeSet that orders elements according to the specified Comparator. ### newTreeSet(Iterable) Creates a TreeSet containing the elements from the given Iterable. ``` -------------------------------- ### Initialize Classes with Reflection - Java Source: https://github.com/google/guava/wiki/ReflectionExplained Ensures that the specified classes are initialized, performing any static initialization. Use of this method is generally discouraged as static state can harm maintainability and testability. ```java Reflection.initialize(Class...) ``` -------------------------------- ### Modifying a Multimap View Source: https://github.com/google/guava/wiki/NewCollectionTypesExplained Modifications to the collection returned by Multimap.get(key) write through to the underlying Multimap. This example shows clearing existing values and adding new ones for a specific key. ```java Set aliceChildren = childrenMultimap.get(alice); aliceChildren.clear(); aliceChildren.add(bob); aliceChildren.add(carol); ``` -------------------------------- ### Avoiding Nested Futures with ExecutorService Source: https://github.com/google/guava/wiki/ListenableFutureExplained This example demonstrates how submitting a Callable that returns a ListenableFuture can lead to nested Futures. Avoid this pattern to ensure proper cancellation propagation and exception handling. ```java executorService.submit(new Callable() { @Override public ListenableFuture call() { return otherExecutorService.submit(otherCallable); } }); ``` -------------------------------- ### View Map as SetMultimap and Invert Source: https://github.com/google/guava/wiki/CollectionUtilitiesExplained Views a Map as a SetMultimap, which is useful for operations that expect a Multimap interface. This example shows how to combine `forMap` with `invertFrom` to invert a map where values are grouped into sets. ```java Map map = ImmutableMap.of("a", 1, "b", 1, "c", 2); SetMultimap multimap = Multimaps.forMap(map); // multimap maps ["a" => {1}, "b" => {1}, "c" => {2}] Multimap inverse = Multimaps.invertFrom(multimap, HashMultimap. create()); // inverse maps [1 => {"a", "b"}, 2 => {"c"}] ``` -------------------------------- ### Create ImmutableSet with `of` and Defensive Copy Source: https://github.com/google/guava/wiki/ImmutableCollectionsExplained Demonstrates creating an ImmutableSet using the `of` method and defensively copying a mutable Set into an ImmutableSet within a constructor. ```java public static final ImmutableSet COLOR_NAMES = ImmutableSet.of( "red", "orange", "yellow", "green", "blue", "purple"); class Foo { final ImmutableSet bars; Foo(Set bars) { this.bars = ImmutableSet.copyOf(bars); // defensive copy! } } ``` -------------------------------- ### Using Guava Table for Graph Representation Source: https://github.com/google/guava/wiki/NewCollectionTypesExplained Demonstrates creating and querying a weighted graph using HashBasedTable. Access rows and columns to retrieve associated data. ```java Table weightedGraph = HashBasedTable.create(); weightedGraph.put(v1, v2, 4); weightedGraph.put(v1, v3, 20); weightedGraph.put(v2, v3, 5); weightedGraph.row(v1); // returns a Map mapping v2 to 4, v3 to 20 weightedGraph.column(v3); // returns a Map mapping v1 to 20, v2 to 5 ```