Advertisement
Satsana

Guava style accessors chaining example

Feb 10th, 2024 (edited)
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. /* OPs POJO classes structure (here https://stackoverflow.com/a/45221474/3225638) */
  2. record A(B item) {
  3.     record B(Long value) {
  4.     }
  5. }
  6.  
  7. /* Unit test example for chained accessors */
  8. @Test
  9. public void testChainAccessors() {
  10.     var list = new ArrayList<A>();
  11.     for (long i = 0L; i < 10; i++)
  12.         list.add(new A(new A.B(i)));
  13.     Stream<A> stream = list.stream();
  14.     final var count = new AtomicLong(0);
  15.     stream.sorted(Comparator.comparing(chain(A::item, A.B::value)))     // <-- example with 2 chained functions
  16.             .map(chain(A::item, A.B::value, Long::toHexString))         // <-- example with 3
  17.             .forEachOrdered(string -> assertThat(string).isEqualTo(Long.toHexString(count.getAndIncrement())));
  18. }
  19.  
  20. /**
  21.  * If you want to avoid casting an accessor method reference into a Function,
  22.  * use a static utility func to do that for us, so you can statically import
  23.  * later
  24.  * Caveats:
  25.  * - it's really hard to use lambdas with primitive types, so you'd
  26.  * have to make sure all your classes use the boxed wrapper types
  27.  * - Don't go into a rabbit hole of using this everywhere and creating
  28.  * functions for every type of lambda combination, it's the compiler's job
  29.  * not yours.. Use C# instead
  30.  */
  31. interface FunctionComposer {
  32.     static <I, T, O> Function<I, O> chain(Function<I, T> first, Function<T, O> second) {
  33.         return first.andThen(second);
  34.     }
  35.  
  36.     // C# style helper utility methods
  37.     static <I, T1, T2, O> Function<I, O> chain(Function<I, T1> f1, Function<T1, T2> f2, Function<T2, O> f3) {
  38.         return f1.andThen(f2).andThen(f3);
  39.     }
  40.    
  41.     /* etc... */
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement