Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* OPs POJO classes structure (here https://stackoverflow.com/a/45221474/3225638) */
- record A(B item) {
- record B(Long value) {
- }
- }
- /* Unit test example for chained accessors */
- @Test
- public void testChainAccessors() {
- var list = new ArrayList<A>();
- for (long i = 0L; i < 10; i++)
- list.add(new A(new A.B(i)));
- Stream<A> stream = list.stream();
- final var count = new AtomicLong(0);
- stream.sorted(Comparator.comparing(chain(A::item, A.B::value))) // <-- example with 2 chained functions
- .map(chain(A::item, A.B::value, Long::toHexString)) // <-- example with 3
- .forEachOrdered(string -> assertThat(string).isEqualTo(Long.toHexString(count.getAndIncrement())));
- }
- /**
- * If you want to avoid casting an accessor method reference into a Function,
- * use a static utility func to do that for us, so you can statically import
- * later
- * Caveats:
- * - it's really hard to use lambdas with primitive types, so you'd
- * have to make sure all your classes use the boxed wrapper types
- * - Don't go into a rabbit hole of using this everywhere and creating
- * functions for every type of lambda combination, it's the compiler's job
- * not yours.. Use C# instead
- */
- interface FunctionComposer {
- static <I, T, O> Function<I, O> chain(Function<I, T> first, Function<T, O> second) {
- return first.andThen(second);
- }
- // C# style helper utility methods
- static <I, T1, T2, O> Function<I, O> chain(Function<I, T1> f1, Function<T1, T2> f2, Function<T2, O> f3) {
- return f1.andThen(f2).andThen(f3);
- }
- /* etc... */
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement