From b6d9690ce151fadc5339ff74db74346e5144ec22 Mon Sep 17 00:00:00 2001 From: sagaofsilence Date: Mon, 6 May 2024 21:16:31 +0530 Subject: [PATCH] Updated method ref tests. --- .../function/custom/MethodReferenceTest.java | 38 ++++++++++++++++--- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/core-java/functional-programming/functional-interfaces/src/test/java/io/reflectoring/function/custom/MethodReferenceTest.java b/core-java/functional-programming/functional-interfaces/src/test/java/io/reflectoring/function/custom/MethodReferenceTest.java index 11e29c32..1e8ae840 100644 --- a/core-java/functional-programming/functional-interfaces/src/test/java/io/reflectoring/function/custom/MethodReferenceTest.java +++ b/core-java/functional-programming/functional-interfaces/src/test/java/io/reflectoring/function/custom/MethodReferenceTest.java @@ -1,6 +1,7 @@ package io.reflectoring.function.custom; import java.math.BigInteger; +import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -11,7 +12,8 @@ /** The Method reference test. */ public class MethodReferenceTest { - @Test + /** Static method reference. */ +@Test void staticMethodReference() { List numbers = List.of(1, -2, 3, -4, 5); List positiveNumbers = numbers.stream().map(Math::abs).toList(); @@ -19,21 +21,47 @@ void staticMethodReference() { number -> Assertions.assertTrue(number > 0, "Number should be positive.")); } - @Test - void instanceMethodReference() { + /** The String number comparator. */ +static class StringNumberComparator implements Comparator { + @Override + public int compare(String o1, String o2) { + if (o1 == null) { + return o2 == null ? 0 : 1; + } else if (o2 == null) { + return -1; + } + return o1.compareTo(o2); + } + } + + /** Instance method reference. */ +@Test + void containingClassInstanceMethodReference() { List numbers = List.of("One", "Two", "Three"); List numberChars = numbers.stream().map(String::length).toList(); numberChars.forEach(length -> Assertions.assertTrue(length > 0, "Number text is not empty.")); } - @Test + /** Instance method reference. */ +@Test + void containingObjectInstanceMethodReference() { + List numbers = List.of("One", "Two", "Three"); + StringNumberComparator comparator = new StringNumberComparator(); + final List sorted = numbers.stream().sorted(comparator::compare).toList(); + final List expected = List.of("One", "Three", "Two"); + Assertions.assertEquals(expected, sorted, "Incorrect sorting."); + } + + /** Instance method arbitrary object particular type. */ +@Test void instanceMethodArbitraryObjectParticularType() { List numbers = List.of(1, 2L, 3.0f, 4.0d); List numberIntValues = numbers.stream().map(Number::intValue).toList(); Assertions.assertEquals(List.of(1, 2, 3, 4), numberIntValues, "Int values are not same."); } - @Test + /** Constructor reference. */ +@Test void constructorReference() { List numbers = List.of("1", "2", "3"); Map numberMapping =