Class Guavate


  • public final class Guavate
    extends Object
    Utilities that help bridge the gap between Java 8 and Google Guava.

    Guava has the FluentIterable concept which is similar to streams. In many ways, fluent iterable is nicer, because it directly binds to the immutable collection classes. However, on balance it seems wise to use the stream API rather than FluentIterable in Java 8.

    • Method Detail

      • concatToList

        @SafeVarargs
        public static <T> ImmutableList<T> concatToList​(Iterable<? extends T>... iterables)
        Concatenates a number of iterables into a single list.

        This is harder than it should be, a method Stream.of(Iterable) would have been appropriate, but cannot be added now.

        Type Parameters:
        T - the type of element in the iterable
        Parameters:
        iterables - the iterables to combine
        Returns:
        the list that combines the inputs
      • concatItemsToList

        @SafeVarargs
        public static <T> ImmutableList<T> concatItemsToList​(Iterable<? extends T> baseList,
                                                             T... additionalItems)
        Concatenates a number of items onto a single base list.

        This returns a new list, the input is unaltered.

        Type Parameters:
        T - the type of element in the iterable
        Parameters:
        baseList - the base list
        additionalItems - the additional items
        Returns:
        the list that combines the inputs
      • concatToSet

        @SafeVarargs
        public static <T> ImmutableSet<T> concatToSet​(Iterable<? extends T>... iterables)
        Concatenates a number of iterables into a single set.

        This is harder than it should be, a method Stream.of(Iterable) would have been appropriate, but cannot be added now.

        Type Parameters:
        T - the type of element in the iterable
        Parameters:
        iterables - the iterables to combine
        Returns:
        the set that combines the inputs
      • combineMaps

        public static <K,​V> ImmutableMap<K,​V> combineMaps​(Map<? extends K,​? extends V> first,
                                                                      Map<? extends K,​? extends V> second)
        Combines two distinct maps into a single map, throwing an exception for duplicate keys.
        Type Parameters:
        K - the type of the keys
        V - the type of the values
        Parameters:
        first - the first map
        second - the second map
        Returns:
        a combined map
        Throws:
        IllegalArgumentException - if the same key is encountered in both maps
      • combineMapsOverwriting

        public static <K,​V> ImmutableMap<K,​V> combineMapsOverwriting​(Map<? extends K,​? extends V> first,
                                                                                 Map<? extends K,​? extends V> second)
        Combines two distinct maps into a single map, choosing the key from the second map in case of duplicates.
        Type Parameters:
        K - the type of the keys
        V - the type of the values
        Parameters:
        first - the first map
        second - the second map
        Returns:
        a combined map
      • combineMaps

        public static <K,​V> ImmutableMap<K,​V> combineMaps​(Map<? extends K,​? extends V> first,
                                                                      Map<? extends K,​? extends V> second,
                                                                      BiFunction<? super V,​? super V,​? extends V> mergeFn)
        Combines two maps into a single map.

        If the maps have shared keys then the merge function is used on the two values and the result is placed in the resulting map.

        Type Parameters:
        K - the type of the keys
        V - the type of the values
        Parameters:
        first - the first map
        second - the second map
        mergeFn - the function used to merge values
        Returns:
        a combined map
      • combineMapsOverwriting

        @SafeVarargs
        public static <K,​V> ImmutableMap<K,​V> combineMapsOverwriting​(Map<? extends K,​? extends V> baseMap,
                                                                                 Map.Entry<? extends K,​? extends V>... additionalEntries)
        Combines a map with new entries, choosing the last entry if there is a duplicate key.
        Type Parameters:
        K - the type of the keys
        V - the type of the values
        Parameters:
        baseMap - the base map
        additionalEntries - the additional entries
        Returns:
        the combined map
      • tryCatchToOptional

        public static <T> Optional<T> tryCatchToOptional​(Supplier<T> supplier)
        Wraps a try-catch block around an expression, avoiding exceptions.

        This converts an exception throwing method into an optional returning one by discarding the exception. In most cases it is better to add a `findXxx()` method to the code you want to call.

        Type Parameters:
        T - the type of the result in the optional
        Parameters:
        supplier - the supplier that might throw an exception
        Returns:
        the value wrapped in an optional, empty if the method returns null or an exception is thrown
      • firstNonEmpty

        @SafeVarargs
        public static <T> Optional<T> firstNonEmpty​(Supplier<Optional<? extends T>>... suppliers)
        Uses a number of suppliers to create a single optional result.

        This invokes each supplier in turn until a non empty optional is returned. As such, not all suppliers are necessarily invoked.

        The Java 8 Optional class does not have an or method, so this provides an alternative.

        Type Parameters:
        T - the type of element in the optional
        Parameters:
        suppliers - the suppliers to combine
        Returns:
        the first non empty optional
      • firstNonEmpty

        @SafeVarargs
        public static <T> Optional<T> firstNonEmpty​(Optional<? extends T>... optionals)
        Chooses the first optional that is not empty.

        The Java 8 Optional class does not have an or method, so this provides an alternative.

        Type Parameters:
        T - the type of element in the optional
        Parameters:
        optionals - the optionals to combine
        Returns:
        the first non empty optional
      • first

        public static <T> Optional<T> first​(Iterable<T> iterable)
        Gets the first value from the iterable, returning empty if the iterable is empty.
        Type Parameters:
        T - the type of element in the optional
        Parameters:
        iterable - the iterable to query
        Returns:
        the first value, empty if empty
      • entry

        public static <K,​V> Map.Entry<K,​V> entry​(K key,
                                                             V value)
        Creates a single Map.Entry.

        The entry is immutable.

        Type Parameters:
        K - the type of the key
        V - the type of the value
        Parameters:
        key - the key
        value - the value
        Returns:
        the map entry
      • list

        @SafeVarargs
        public static <T> ImmutableList<T> list​(T first,
                                                T... remaining)
        Converts a list from the first element and remaining varargs.

        This can be used to create a list of at least size one.

        Type Parameters:
        T - the type of the elements
        Parameters:
        first - the first element
        remaining - the remaining elements
        Returns:
        a list formed from the first and remaining elements
      • set

        @SafeVarargs
        public static <T> ImmutableSet<T> set​(T first,
                                              T... remaining)
        Converts a set from the first element and remaining varargs.

        This can be used to create a set of at least size one. The input may contain duplicates, which will be combined.

        Type Parameters:
        T - the type of the elements
        Parameters:
        first - the first element
        remaining - the remaining elements
        Returns:
        a set formed from the first and remaining elements
      • boxed

        public static Optional<Integer> boxed​(OptionalInt optional)
        Boxes an OptionalInt.

        OptionalInt has almost no useful methods and no easy way to convert it to an Optional. This method provides the conversion to Optional<Integer>.

        Parameters:
        optional - the OptionalInt
        Returns:
        an equivalent optional
      • boxed

        public static Optional<Long> boxed​(OptionalLong optional)
        Boxes an OptionalLong.

        OptionalLong has almost no useful methods and no easy way to convert it to an Optional. This method provides the conversion to Optional<Long>.

        Parameters:
        optional - the OptionalLong
        Returns:
        an equivalent optional
      • boxed

        public static Optional<Double> boxed​(OptionalDouble optional)
        Boxes an OptionalDouble.

        OptionalDouble has almost no useful methods and no easy way to convert it to an Optional. This method provides the conversion to Optional<Double>.

        Parameters:
        optional - the OptionalDouble
        Returns:
        an equivalent optional
      • stream

        public static <T> Stream<T> stream​(Iterable<T> iterable)
        Converts an iterable to a serial stream.

        This is harder than it should be, a method Stream.of(Iterable) would have been appropriate, but cannot be added now.

        Type Parameters:
        T - the type of element in the iterable
        Parameters:
        iterable - the iterable to convert
        Returns:
        a stream of the elements in the iterable
      • stream

        public static <T> Stream<T> stream​(Optional<T> optional)
        Converts an optional to a stream with zero or one elements.
        Type Parameters:
        T - the type of optional element
        Parameters:
        optional - the optional
        Returns:
        a stream containing a single value if the optional has a value, else a stream with no values.
      • in

        public static <T> Iterable<T> in​(Stream<T> stream)
        Converts a stream to an iterable for use in the for-each statement.

        For some use cases this approach is nicer than Stream.forEach(Consumer). Notably code that mutates a local variable or has to handle checked exceptions will benefit.

          for (Item item : in(stream)) {
            // lazily use each item in the stream
          }
         

        NOTE: The result of this method can only be iterated once, which does not meet the expected specification of Iterable. Use in the for-each statement is safe as it will only be called once.

        Type Parameters:
        T - the type of stream element
        Parameters:
        stream - the stream
        Returns:
        an iterable representation of the stream that can only be invoked once
      • inOptional

        public static <T> Iterable<T> inOptional​(Optional<T> optional)
        Converts an optional to an iterable for use in the for-each statement.

        For some use cases this approach is nicer than Optional.isPresent() followed by Optional.get().

          for (Item item : inOptional(optional)) {
            // use the optional value, code not called if the optional is empty
          }
         

        NOTE: This method is intended only for use with the for-each statement. It does in fact return a general purpose Iterable, but the method name is focussed on the for-each use case.

        Type Parameters:
        T - the type of optional element
        Parameters:
        optional - the optional
        Returns:
        an iterable representation of the optional
      • inNullable

        public static <T> Iterable<T> inNullable​(T nullable)
        Converts a nullable value to an iterable for use in the for-each statement.

        In most cases if (nullable != null) would be preferred.

          for (Item item : inNullable(nullable)) {
            // use the nullable value, code not called if the value is null
          }
         

        NOTE: This method is intended only for use with the for-each statement. It does in fact return a general purpose Iterable, but the method name is focussed on the for-each use case.

        Type Parameters:
        T - the type of the nullable value
        Parameters:
        nullable - the nullable value
        Returns:
        an iterable representation of the nullable
      • zipWithIndex

        public static <T> Stream<ObjIntPair<T>> zipWithIndex​(Stream<T> stream)
        Creates a stream that wraps a stream with the index.

        Each input object is decorated with an ObjIntPair. The int is the index of the element in the stream.

        See also MapStream.zipWithIndex(Stream).

        Type Parameters:
        T - the type of the stream
        Parameters:
        stream - the stream to index
        Returns:
        a stream of pairs, containing the element and index
      • zip

        public static <A,​B> Stream<Pair<A,​B>> zip​(Stream<A> stream1,
                                                              Stream<B> stream2)
        Creates a stream that combines two other streams, continuing until either stream ends.

        Each pair of input objects is combined into a Pair.

        See also MapStream.zip(Stream, Stream).

        Type Parameters:
        A - the type of the first stream
        B - the type of the second stream
        Parameters:
        stream1 - the first stream
        stream2 - the first stream
        Returns:
        a stream of pairs, one from each stream
      • not

        public static <R> Predicate<R> not​(Predicate<R> predicate)
        Returns a predicate that negates the original.

        The JDK provides Predicate.negate() however this requires a predicate. Sometimes, it can be useful to have a static method to achieve this.

          stream.filter(not(String::isEmpty))
         
        Type Parameters:
        R - the type of the object the predicate works on
        Parameters:
        predicate - the predicate to negate
        Returns:
        the negated predicate
      • ensureOnlyOne

        public static <T> BinaryOperator<T> ensureOnlyOne()
        Reducer used in a stream to ensure there is no more than one matching element.

        This method returns an operator that can be used with Stream.reduce(BinaryOperator) that returns either zero or one elements from the stream. Unlike Stream.findFirst() or Stream.findAny(), this approach ensures an exception is thrown if there is more than one element in the stream.

        This would be used as follows (with a static import):

           stream.filter(...).reduce(ensureOnlyOne()).get();
         
        Type Parameters:
        T - the type of element in the stream
        Returns:
        the operator
      • casting

        public static <T,​R extends T> Function<T,​R> casting​(Class<R> cls)
        Function used in a stream to cast instances to a particular type without filtering.

        This method returns a function that can be used with Stream.map(Function) to cast elements in a stream to a particular type, throwing an exception if any element is not of the specified type.

        This would be used as follows (with a static import):

           stream.map(casting(Foo.class));
         

        This replaces code of the form:

           stream.map(Foo.class::cast);
         
        Type Parameters:
        T - the type of element in the input stream
        R - the type of element in the output stream
        Parameters:
        cls - the type of element in the output stream
        Returns:
        the function
      • filtering

        public static <T,​R extends T> Function<T,​Stream<R>> filtering​(Class<R> cls)
        Function used in a stream to filter instances to a particular type.

        This method returns a function that can be used with Stream.flatMap(Function) to filter elements in a stream to a particular type.

        This would be used as follows (with a static import):

           stream.flatMap(filtering(Foo.class));
         

        This replaces code of the form:

           stream.filter(Foo.class::isInstance).map(Foo.class::cast);
         
        Type Parameters:
        T - the type of element in the input stream
        R - the type of element in the output stream
        Parameters:
        cls - the type of element in the output stream
        Returns:
        the function
      • filteringOptional

        public static <T> Function<Optional<T>,​Stream<T>> filteringOptional()
        Function used in a stream to filter optionals.

        This method returns a function that can be used with Stream.flatMap(Function) to filter optional elements in a stream. The resulting stream only contains the optional elements that are present.

        This would be used as follows (with a static import):

           stream.flatMap(filteringOptional());
         

        This replaces code of the form:

           stream.filter(Optional::isPresent).map(Optional::get);
         
        Type Parameters:
        T - the type of element in the output stream
        Returns:
        the function
      • toOptional

        public static <T> Collector<T,​?,​Optional<T>> toOptional()
        Collector used at the end of a stream to extract either zero or one elements.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an Optional. The collector throws IllegalArgumentException if the stream consists of two or more elements. The collector throws NullPointerException if the stream consists of a null element.

        Type Parameters:
        T - the type of element in the list
        Returns:
        the immutable list collector
      • toImmutableList

        public static <T> Collector<T,​ImmutableList.Builder<T>,​ImmutableList<T>> toImmutableList()
        Collector used at the end of a stream to build an immutable list.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableList.

        Type Parameters:
        T - the type of element in the list
        Returns:
        the immutable list collector
      • splittingBySize

        public static <T> Collector<T,​?,​ImmutableList<ImmutableList<T>>> splittingBySize​(int size)
        Collector used at the end of a stream to build an immutable list of immutable lists of size equal to or less than size. For example, the following list [a, b, c, d, e] with a partition size of 2 will give [[a, b], [c, d], [e]].

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableList of ImmutableList.

        Type Parameters:
        T - the type of element in the list
        Parameters:
        size - the size of the partitions of the original list
        Returns:
        the immutable list of lists collector
      • toImmutableSet

        public static <T> Collector<T,​ImmutableSet.Builder<T>,​ImmutableSet<T>> toImmutableSet()
        Collector used at the end of a stream to build an immutable set.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableSet.

        Type Parameters:
        T - the type of element in the set
        Returns:
        the immutable set collector
      • toImmutableSortedSet

        public static <T extends Comparable<?>> Collector<T,​ImmutableSortedSet.Builder<T>,​ImmutableSortedSet<T>> toImmutableSortedSet()
        Collector used at the end of a stream to build an immutable sorted set.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableSet.

        Type Parameters:
        T - the type of element in the sorted set
        Returns:
        the immutable sorted set collector
      • toImmutableSortedSet

        public static <T> Collector<T,​ImmutableSortedSet.Builder<T>,​ImmutableSortedSet<T>> toImmutableSortedSet​(Comparator<? super T> comparator)
        Collector used at the end of a stream to build an immutable sorted set.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableSet.

        Type Parameters:
        T - the type of element in the sorted set
        Parameters:
        comparator - the comparator
        Returns:
        the immutable sorted set collector
      • toImmutableMultiset

        public static <T> Collector<T,​ImmutableMultiset.Builder<T>,​ImmutableMultiset<T>> toImmutableMultiset()
        Collector used at the end of a stream to build an immutable multiset.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableMultiset.

        Type Parameters:
        T - the type of element in the multiset
        Returns:
        the immutable multiset collector
      • toImmutableMap

        public static <T,​K> Collector<T,​?,​ImmutableMap<K,​T>> toImmutableMap​(Function<? super T,​? extends K> keyExtractor)
        Collector used at the end of a stream to build an immutable map.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableMap, retaining insertion order.

        This returns a map by extracting a key from each element. The input stream must resolve to unique keys. The value associated with each key is the stream element. See Collectors.toMap(Function, Function) for more details.

        Type Parameters:
        T - the type of the stream elements
        K - the type of the keys in the result map
        Parameters:
        keyExtractor - function to produce keys from stream elements
        Returns:
        the immutable map collector
        Throws:
        IllegalArgumentException - if the same key is generated twice
      • toImmutableMap

        public static <T,​K,​V> Collector<T,​?,​ImmutableMap<K,​V>> toImmutableMap​(Function<? super T,​? extends K> keyExtractor,
                                                                                                            Function<? super T,​? extends V> valueExtractor)
        Collector used at the end of a stream to build an immutable map.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableMap, retaining insertion order.

        This returns a map by converting each stream element to a key and value. The input stream must resolve to unique keys. See Collectors.toMap(Function, Function) for more details.

        Type Parameters:
        T - the type of the stream elements
        K - the type of the keys in the result map
        V - the type of the values in the result map
        Parameters:
        keyExtractor - function to produce keys from stream elements
        valueExtractor - function to produce values from stream elements
        Returns:
        the immutable map collector
        Throws:
        IllegalArgumentException - if the same key is generated twice
      • toImmutableMap

        public static <T,​K,​V> Collector<T,​Map<K,​V>,​ImmutableMap<K,​V>> toImmutableMap​(Function<? super T,​? extends K> keyExtractor,
                                                                                                                         Function<? super T,​? extends V> valueExtractor,
                                                                                                                         BiFunction<? super V,​? super V,​? extends V> mergeFn)
        Collector used at the end of a stream to build an immutable map.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableMap, retaining insertion order.

        This returns a map by converting each stream element to a key and value. If the same key is generated more than once the merge function is applied to the values and the return value of the function is used as the value in the map.

        Type Parameters:
        T - the type of the stream elements
        K - the type of the keys in the result map
        V - the type of the values in the result map
        Parameters:
        keyExtractor - function to produce keys from stream elements
        valueExtractor - function to produce values from stream elements
        mergeFn - function to merge values with the same key
        Returns:
        the immutable map collector
      • toImmutableSortedMap

        public static <T,​K extends Comparable<?>> Collector<T,​?,​ImmutableSortedMap<K,​T>> toImmutableSortedMap​(Function<? super T,​? extends K> keyExtractor)
        Collector used at the end of a stream to build an immutable sorted map.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableSortedMap.

        This returns a map by extracting a key from each element. The input stream must resolve to unique keys. The value associated with each key is the stream element. See Collectors.toMap(Function, Function) for more details.

        Type Parameters:
        T - the type of the stream elements
        K - the type of the keys in the result map
        Parameters:
        keyExtractor - function to produce keys from stream elements
        Returns:
        the immutable sorted map collector
        Throws:
        IllegalArgumentException - if the same key is generated twice
      • toImmutableSortedMap

        public static <T,​K extends Comparable<?>,​V> Collector<T,​?,​ImmutableSortedMap<K,​V>> toImmutableSortedMap​(Function<? super T,​? extends K> keyExtractor,
                                                                                                                                              Function<? super T,​? extends V> valueExtractor)
        Collector used at the end of a stream to build an immutable sorted map.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableSortedMap.

        This returns a map by converting each stream element to a key and value. The input stream must resolve to unique keys. See Collectors.toMap(Function, Function) for more details.

        Type Parameters:
        T - the type of the stream elements
        K - the type of the keys in the result map
        V - the type of the values in the result map
        Parameters:
        keyExtractor - function to produce keys from stream elements
        valueExtractor - function to produce values from stream elements
        Returns:
        the immutable sorted map collector
        Throws:
        IllegalArgumentException - if the same key is generated twice
      • toImmutableSortedMap

        public static <T,​K extends Comparable<?>,​V> Collector<T,​?,​ImmutableSortedMap<K,​V>> toImmutableSortedMap​(Function<? super T,​? extends K> keyExtractor,
                                                                                                                                              Function<? super T,​? extends V> valueExtractor,
                                                                                                                                              BiFunction<? super V,​? super V,​? extends V> mergeFn)
        Collector used at the end of a stream to build an immutable sorted map.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableSortedMap.

        This returns a map by converting each stream element to a key and value. See Collectors.toMap(Function, Function) for more details.

        Type Parameters:
        T - the type of the stream elements
        K - the type of the keys in the result map
        V - the type of the values in the result map
        Parameters:
        keyExtractor - function to produce keys from stream elements
        valueExtractor - function to produce values from stream elements
        mergeFn - function to merge values with the same key
        Returns:
        the immutable sorted map collector
      • toImmutableListMultimap

        public static <T,​K> Collector<T,​?,​ImmutableListMultimap<K,​T>> toImmutableListMultimap​(Function<? super T,​? extends K> keyExtractor)
        Collector used at the end of a stream to build an immutable multimap.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableListMultimap.

        This returns a multimap by extracting a key from each element. The value associated with each key is the stream element. Stream elements may be converted to the same key, with the values forming a multimap list. See Collectors.groupingBy(Function) for more details.

        Type Parameters:
        T - the type of the stream elements
        K - the type of the keys in the result multimap
        Parameters:
        keyExtractor - function to produce keys from stream elements
        Returns:
        the immutable multimap collector
      • toImmutableListMultimap

        public static <T,​K,​V> Collector<T,​?,​ImmutableListMultimap<K,​V>> toImmutableListMultimap​(Function<? super T,​? extends K> keyExtractor,
                                                                                                                              Function<? super T,​? extends V> valueExtractor)
        Collector used at the end of a stream to build an immutable multimap.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableListMultimap.

        This returns a multimap by converting each stream element to a key and value. Stream elements may be converted to the same key, with the values forming a multimap list.

        Type Parameters:
        T - the type of the stream elements
        K - the type of the keys in the result multimap
        V - the type of the values in the result multimap
        Parameters:
        keyExtractor - function to produce keys from stream elements
        valueExtractor - function to produce values from stream elements
        Returns:
        the immutable multimap collector
      • toImmutableSetMultimap

        public static <T,​K> Collector<T,​?,​ImmutableSetMultimap<K,​T>> toImmutableSetMultimap​(Function<? super T,​? extends K> keyExtractor)
        Collector used at the end of a stream to build an immutable multimap.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableSetMultimap.

        This returns a multimap by extracting a key from each element. The value associated with each key is the stream element. Stream elements may be converted to the same key, with the values forming a multimap set. See Collectors.groupingBy(Function) for more details.

        Type Parameters:
        T - the type of the stream elements
        K - the type of the keys in the result multimap
        Parameters:
        keyExtractor - function to produce keys from stream elements
        Returns:
        the immutable multimap collector
      • toImmutableSetMultimap

        public static <T,​K,​V> Collector<T,​?,​ImmutableSetMultimap<K,​V>> toImmutableSetMultimap​(Function<? super T,​? extends K> keyExtractor,
                                                                                                                            Function<? super T,​? extends V> valueExtractor)
        Collector used at the end of a stream to build an immutable multimap.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableSetMultimap.

        This returns a multimap by converting each stream element to a key and value. Stream elements may be converted to the same key, with the values forming a multimap set.

        Type Parameters:
        T - the type of the stream elements
        K - the type of the keys in the result multimap
        V - the type of the values in the result multimap
        Parameters:
        keyExtractor - function to produce keys from stream elements
        valueExtractor - function to produce values from stream elements
        Returns:
        the immutable multimap collector
      • entriesToImmutableMap

        public static <K,​V> Collector<Map.Entry<? extends K,​? extends V>,​?,​ImmutableMap<K,​V>> entriesToImmutableMap()
        Collector used at the end of a stream to build an immutable map from a stream containing map entries. This is a common case if a map's entrySet has undergone a filter operation. For example:
           
               Map<String, Integer> input = ImmutableMap.of("a", 1, "b", 2, "c", 3, "d", 4, "e", 5);
               ImmutableMap<String, Integer> output =
                 input.entrySet()
                   .stream()
                   .filter(e -> e.getValue() % 2 == 1)
                   .collect(entriesToImmutableMap());
        
               // Produces map with "a" -> 1, "c" -> 3, "e" -> 5
           
         

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableMap.

        This returns a map by converting each Map.Entry to a key and value. The input stream must resolve to unique keys.

        Type Parameters:
        K - the type of the keys in the result map
        V - the type of the values in the result map
        Returns:
        the immutable map collector
        Throws:
        IllegalArgumentException - if the same key is generated twice
      • entriesToImmutableMap

        public static <K,​V> Collector<Map.Entry<? extends K,​? extends V>,​?,​ImmutableMap<K,​V>> entriesToImmutableMap​(BiFunction<? super V,​? super V,​? extends V> mergeFn)
        Collector used at the end of a stream to build an immutable map from a stream containing map entries which could have duplicate keys.

        This is a common case if a map's entrySet has undergone a map operation. For example:

           
               Map<Integer, String> input = ImmutableMap.of(1, "a", 2, "b", 3, "c", 4, "d", 5, "e");
               ImmutableMap<String, Integer> output =
                 input.entrySet()
                   .stream()
                   .map(e -> Guavate.entry(e.getKey() % 2, e.getValue()))
                   .collect(entriesToImmutableMap(String::concat));
        
               // Produces map with 0 -> "bd", 1 -> "ace"
           
         

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableMap.

        This returns a map by converting each Map.Entry to a key and value.

        Type Parameters:
        K - the type of the keys in the result map
        V - the type of the values in the result map
        Parameters:
        mergeFn - function to merge values with the same key
        Returns:
        the immutable map collector
      • pairsToImmutableMap

        public static <K,​V> Collector<Pair<? extends K,​? extends V>,​?,​ImmutableMap<K,​V>> pairsToImmutableMap()
        Collector used at the end of a stream to build an immutable map from a stream containing pairs. This is a common case if a map's entrySet has undergone a map operation with the Map.Entry converted to a Pair. For example:
           
               Map<String, Integer> input = ImmutableMap.of("a", 1, "b", 2, "c", 3, "d", 4);
               ImmutableMap<String, Double> output =
                 input.entrySet()
                   .stream()
                   .map(e -> Pair.of(e.getKey().toUpperCase(), Math.pow(e.getValue(), 2)))
                   .collect(pairsToImmutableMap());
        
               // Produces map with "A" -> 1.0, "B" -> 4.0, "C" -> 9.0, "D" -> 16.0
           
         

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing streams to be gathered into an ImmutableMap.

        This returns a map by converting each stream element to a key and value. The input stream must resolve to unique keys.

        Type Parameters:
        K - the type of the keys in the result map
        V - the type of the values in the result map
        Returns:
        the immutable map collector
        Throws:
        IllegalArgumentException - if the same key is generated twice
      • combineFuturesAsList

        public static <T> CompletableFuture<List<T>> combineFuturesAsList​(List<? extends CompletableFuture<? extends T>> futures)
        Converts a list of futures to a single future, combining the values into a list.

        The CompletableFuture.allOf(CompletableFuture...) method is useful but it returns Void. This method combines the futures but also returns the resulting value as a list. Effectively, this converts List<CompletableFuture<T>> to CompletableFuture<List<T>>.

        If any input future completes exceptionally, the result will also complete exceptionally.

        Type Parameters:
        T - the type of the values in the list
        Parameters:
        futures - the futures to convert, may be empty
        Returns:
        a future that combines the input futures as a list
      • toCombinedFuture

        public static <T,​S extends CompletableFuture<? extends T>> Collector<S,​?,​CompletableFuture<List<T>>> toCombinedFuture()
        Collector used at the end of a stream to convert a list of futures to a single future, combining the values into a list.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing a stream of futures to be combined into a single future. This converts List<CompletableFuture<T>> to CompletableFuture<List<T>>.

        Type Parameters:
        S - the type of the input futures
        T - the type of the values
        Returns:
        a collector that combines the input futures as a list
      • combineFuturesAsMap

        public static <K,​V,​F extends CompletableFuture<? extends V>> CompletableFuture<Map<K,​V>> combineFuturesAsMap​(Map<? extends K,​? extends F> futures)
        Converts a map of futures to a single future.

        This is similar to combineFuturesAsList(List) but for maps. Effectively, this converts Map<K, CompletableFuture<V>> to CompletableFuture<Map<K, V>>.

        If any input future completes exceptionally, the result will also complete exceptionally. The results must be non-null.

        Type Parameters:
        K - the type of the keys in the map
        V - the type of the values in the map
        F - the type of the futures, must not be Void
        Parameters:
        futures - the futures to convert, may be empty
        Returns:
        a future that combines the input futures as a map
      • toCombinedFutureMap

        public static <K,​V,​F extends CompletableFuture<? extends V>> Collector<Map.Entry<? extends K,​? extends F>,​?,​CompletableFuture<Map<K,​V>>> toCombinedFutureMap()
        Collector used at the end of a stream to convert a map of futures to a single future, combining the values into a map.

        A collector is used to gather data at the end of a stream operation. This method returns a collector allowing a stream of futures to be combined into a single future. This converts Map<K, CompletableFuture<V>> to CompletableFuture<Map<K, V>>.

        Type Parameters:
        K - the type of the keys in the map
        V - the type of the values in the map
        F - the type of the input futures
        Returns:
        a collector that combines the input futures as a map
      • poll

        public static <T> CompletableFuture<T> poll​(ScheduledExecutorService executorService,
                                                    Duration initialDelay,
                                                    Duration frequency,
                                                    Supplier<T> pollingTask)
        Polls on a regular frequency until a result is found.

        Polling is performed via the specified supplier, which must return null until the result is available. If the supplier throws an exception, polling will stop and the future will complete exceptionally.

        If the future is cancelled, the polling will also be cancelled. It is advisable to consider using a timeout when querying the future.

        In most cases, there needs to be an initial request, which might return an identifier to query. This pattern may be useful for that case:

          return CompletableFuture.supplyAsync(initPollingReturningId(), executorService)
              .thenCompose(id -> poll(executorService, delay, freq, performPolling(id)));
          });
         
        Type Parameters:
        T - the result type
        Parameters:
        executorService - the executor service to use for polling
        initialDelay - the initial delay before starting to poll
        frequency - the frequency to poll at
        pollingTask - the task used to poll, returning null when not yet complete
        Returns:
        the future representing the asynchronous operation
      • namedThreadFactory

        public static ThreadFactoryBuilder namedThreadFactory()
        Creates a ThreadFactoryBuilder which names new threads with the name of the calling class plus a unique integer.
        Returns:
        the thread factory builder
      • namedThreadFactory

        public static ThreadFactoryBuilder namedThreadFactory​(String threadNamePrefix)
        Creates a ThreadFactoryBuilder which names new threads with the given name prefix plus a unique integer.
        Parameters:
        threadNamePrefix - the name which new thread names should be prefixed by
        Returns:
        the thread factory builder
      • genericClass

        public static <T,​S extends T> Class<S> genericClass​(Class<T> cls)
        Returns a generified Class instance.

        It is not possible in Java generics to get a Class object with the desired generic signature, such as Class<List<String>>. This method provides a way to get such a value. The method returns the input parameter, but the compiler sees the result as being a different type.

        Note that the generic part of the resulting type is not checked and can be unsound. The safest choice is to explicitly specify the type you want, by assigning to a variable or constant:

           Class<List<String>> cls = genericClass(List.class);
         
        Type Parameters:
        T - the partially specified generic type, such as List from a constant such as List.class
        S - the fully specified generic type, such as List<String>
        Parameters:
        cls - the class instance to base the result in, such as List.class
        Returns:
        the class instance from the input, with whatever generic parameter is desired
      • callerClass

        public static Class<?> callerClass​(int callStackDepth)
        Finds the caller class.

        This takes an argument which is the number of stack levels to look back. This will be 2 to return the caller of this method, 3 to return the caller of the caller, and so on.

        Parameters:
        callStackDepth - the depth of the stack to look back
        Returns:
        the caller class
      • substringBeforeFirst

        public static String substringBeforeFirst​(String str,
                                                  String separator)
        Gets the substring before the first occurrence of the separator.

        This returns the string before the first occurrence of the separator. If the separator is not found, the input is returned.

        Parameters:
        str - the input string to search
        separator - the separator to find
        Returns:
        the substring
      • substringAfterFirst

        public static String substringAfterFirst​(String str,
                                                 String separator)
        Gets the substring after the first occurrence of the separator.

        This returns the string after the first occurrence of the separator. If the separator is not found, the input is returned.

        Parameters:
        str - the input string to search
        separator - the separator to find
        Returns:
        the substring
      • substringBeforeLast

        public static String substringBeforeLast​(String str,
                                                 String separator)
        Gets the substring before the last occurrence of the separator.

        This returns the string before the last occurrence of the separator. If the separator is not found, the input is returned.

        Parameters:
        str - the input string to search
        separator - the separator to find
        Returns:
        the substring
      • substringAfterLast

        public static String substringAfterLast​(String str,
                                                String separator)
        Gets the substring after the last occurrence of the separator.

        This returns the string after the last occurrence of the separator. If the separator is not found, the input is returned.

        Parameters:
        str - the input string to search
        separator - the separator to find
        Returns:
        the substring