Class Funnel<T>

  • Type Parameters:
    T - the output type

    public final class Funnel<T>
    extends java.lang.Object
    A funnel that dispatches a sequence of inputs through arbitrary batch conversions while maintaining first-in-first-out order. For example, the following code can either batch load users from a user store, or batch load from third party user store, or else create a dummy user immediately without conversion:
    
     Funnel<User> funnel = new Funnel<>();
     Funnel.Batch<Long, User> userStoreBatch = funnel.through(userStore::loadUsers);
     Funnel.Batch<ThirdPartyUser, User> thirdPartyBatch = funnel.through(thirdPartyClient::loadUsers);
     for (UserDto dto : users) {
       if (dto.hasUserId()) {
         userStoreBatch.accept(dto.getUserId());
       } else if (dto.hasThirdParty()) {
         thirdPartyBatch.accept(dto.getThirdParty());
       } else {
         funnel.add(createDummyUser(dto));
       }
     }
     List<User> users = funnel.run();
     

    Elements flow out of the funnel in the same order as they enter, regardless of which Funnel.Batch converted them, or if they were directly added into the funnel without conversion.

    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static class  Funnel.Batch<F,​T>
      Holds the elements to be converted through a single batch conversion.
    • Constructor Summary

      Constructors 
      Constructor Description
      Funnel()  
    • Method Summary

      Modifier and Type Method Description
      void add​(T element)
      Adds element to the funnel.
      java.util.List<T> run()
      Runs all batch conversions and returns conversion results together with elements added as is, in encounter order.
      <F> Funnel.Batch<F,​T> through​(java.util.function.Function<? super java.util.List<F>,​? extends java.util.Collection<? extends T>> converter)
      Returns a Funnel.Batch accepting elements that, when run() is called, will be converted together in a batch through converter.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • Funnel

        public Funnel()
    • Method Detail

      • through

        public <F> Funnel.Batch<F,​T> through​(java.util.function.Function<? super java.util.List<F>,​? extends java.util.Collection<? extends T>> converter)
        Returns a Funnel.Batch accepting elements that, when run() is called, will be converted together in a batch through converter.
      • add

        public void add​(T element)
        Adds element to the funnel.
      • run

        public java.util.List<T> run()
        Runs all batch conversions and returns conversion results together with elements added as is, in encounter order.