So I was reading generics and functional interfaces. There were two ways shown - Using Lambdas, Using method references. There were below examples used:
Predicate<String> ref = String::isEmpty;
Java uses the parameter supplied at runtime as the instance on which isEmpty is called. This is allowed because isEmpty() is an instance method in String class and doesn't take any parameter.
My question is, why does it shows compile error when I use the below line of code:
Supplier<Integer> ref2 = Random::nextInt;
After all, nextInt() is an instance method in Random class just like isEmpty() in String class and it doesn't take parameter either.
Random::nextInt is an instance method, so it needs an instance of Random in order to be called. Just like you can't call String::isEmpty without a String. That's why String::isEmpty is a match for Predicate<String>: it takes a String as an argument and returns a boolean.
Similarly, Random::nextInt needs an instance of Random as an argument, and returns an int. So it could be used as a Function<Random, Integer>; but not a Supplier<Integer>, because it cannot be called without arguments.
Alternatively, if you have an instance of Random, you can use a reference to the nextInt method of that particular instance as a Supplier.
Random random = new Random();
Supplier<Integer> randomIntSupplier = random::nextInt;
Related
According to Oracle Documentation, the String::compareToIgnoreCase is also a valid method reference, my question is that compareToIgnoreCase is not a static method, in other words, compareToIgnoreCase must be attached to a specific String instance. So how does JDK know which instance of String I refer when I use String::compareToIgnoreCase ?
Consider the following example using toUpperCase which is also an instance method.
It works in this case because the Stream item that is being handled is of the same type as the class of the method being invoked. So the item actually invokes the method directly.
So for
Stream.of("abcde").map(String::toUpperCase).forEach(System.out::println);
the String::toUpperCase call will be the same as "abcde".toUpperCase()
If you did something like this:
Stream.of("abcde").map(OtherClass::toUpperCase).forEach(System.out::println);
"abcde" is not a type of OtherClass so the OtherClass would need to look like the following for the stream to work.
class OtherClass {
public static String toUpperCase(String s) {
return s.toUpperCase();
}
}
String::compareToIgnoreCase is not used such as str1.compareToIgnoreCase(str2) would be.
It actually is used as a comparator.
E.g. you could compare it to
Arrays.sort(someIntegerArray, Collections.reverseOrder())
but in this case it would be
Arrays.sort(someStringArray, String::compareToIgnoreCase)
It is like there is an additional parameter, the actual instance, involved.
Example for String::compareToIgnoreCase:
ToIntBiFunction<String, String> func = String::compareToIgnoreCase;
int result = func.applyAsInt("ab", "cd"); // some negative number expected
We get a ToIntBiFunction - a two parameter function returning int - since the result is an int, the first parameter correspond to this of compareToIgnoreCase and the second function parameter is the parameter passed to compareToIgnoreCase.
maybe a bit easier:
ToIntFunction<String> f = String::length; // function accepting String, returning int
int length = f.applyAsInt("abc"); // 3
length does not accept any parameter, but the first argument of the function is used as the instance length is called on
The examples above are very abstract, just to show the types involved. The functions are mostly used directly in some method call, no need to use an intermediate variable
for example in Scanner we have
obj.next()
but we can call another method after next()
obj.next().charAt(0)
how can I make similar thing for example
obj.getName().toLowerCase()
What you have observed – with examples like obj.getName().toLowerCase() – is that when the return type of a method call is itself some other object, then you can immediately call a new method on that newly returned object.
Here's another example: String s = String.class.getName().toLowerCase();. This example could be rewritten like so:
Class<String> stringClass = String.class;
String name = stringClass.getName();
String s = name.toLowerCase();
Both of the one-line and multi-line version of this code result in a String object, referenced by s, which contains the value "java.lang.string".
Note that chaining method calls together is not possible if the return type isn't an object, such as an integer value. For example, here's a method call that results in a primitive long value, which isn't an object, so you can't call any methods on that result – that is, something like millis.hashCode() isn't possible.
long millis = System.currentTimeMillis();
To address your primary question finally: you can create this same behavior by creating methods that return objects instead of primitives (int, long, byte, etc.).
I have the following code:
public class BiPredicateTest {
public static void main(String[] args) {
BiPredicate<List<Integer>, Integer> listContains = List::contains;
List aList = Arrays.asList(10, 20, 30);
System.out.println(listContains.test(aList, 20)); // prints true magically?
}
}
In the statement listContains.test(aList, 20), how is it that the method "contains" is getting called on the first argument and the second argument is passed in as a parameter? Something equivalent to:
System.out.println(aList.contains(20));
In other words, how does the statement listContains.test(aList, 20) get translated to aList.contains(20)?
Is this how java 8 BiPredicate work? Could someone explain how the magic is happening (with some references)?
This is not a duplicate post. This differs from "What does “an Arbitrary Object of a Particular Type” mean in java 8?" in that its not explicitly passing method reference around. It is very clear how method reference is being passed around in the post you reference. The array instance on which the method is being called is passed as an argument to Arrays.sort(). In my case, how the method "contains" is being called on aList is not apparent. I am looking for a reference or explanation as to how its working.
It seems some individuals prefer to down vote instead of provide reference or explanation. They give the impression that they have knowledge but refuse to share it.
BiPredicate is an interface which has only one method, test.
public interface BiPredicate<A,B> {
boolean test(A a, B b);
}
Interfaces which have only one method are called functional interfaces. Previous to Java 8, you would often times have to implement these interfaces using an anonymous class, just to create a wrapper for a certain method call with the same signature. Like this:
BiPredicate<List<Integer>,Integer> listContains = new BiPredicate<>() {
#Override
public boolean test(List<Integer> list, Integer num) {
return list.contains(num);
}
};
In Java 8, method references were added, which allowed for a much shorter syntax and more efficient bytecode for this pattern. In a method reference, you can specify a method or constructor which has the same signature as the type arguments for the interface. When you make a method reference using a class type, it assigns the class type as the first generic argument of the functional interface being used. This means whatever parameter which uses that generic type will need to be an instance of the class.
Even if the instance method normally doesn't take any parameters, a method reference can still be used which takes an instance as the parameter. For example:
Predicate<String> pred = String::isEmpty;
pred.test(""); // true
For more information, see the Java Tutorial for Method References.
Can anybody explain this how this line of code works:
Rational sum = a.add(b).add(c);
I don't understand how object b (which is an argument) is receiving a method?
This is called method chaining. The method add() actually returns a reference of the currently modified object or a new object of the same type on which the method was invoked. Say suppose the object referred to by a is a BigInteger , when you invoke a.add(b) , it returns a BigInteger object whose value is a+b , and hence you can invoke .add(c) on that object again.
Rational sum = a.add(b).add(c);
// is equivalent to
Rational temp = a.add(b);
Rational sum = temp.add(c);
Method chaining is not required. It only potentially improves readability and reduces the amount of source code. It is the core concept behind building a fluent interface.
A sample illustration:
This practice is used mostly in Builder pattern, you can find this pattern in API itself in StringBuilder class.
I don't understand how object b (which is an argument) is receiving a method?
No your understanding is wrong , a.add(b) means you are invoking method add() on object a and passing it a reference of object b . The resultant object which the method a.add(b) returns is of the same type as a , and then in succession you call the method .add(c) on the returned object passing a reference of object c to that method.
Its fluent chaining
Each method in the chain has to return a class or an interface. The next method in the chain has to be a part of the returned class.
in your case a.add(b) returning some calss/interface and then calling add(c) on that and that method returns your sum
I am trying to read some Java code from a tutorial, I don't understand the line:
public Weatherman(Integer... zips) {
I don't understand what the ... represents if it was just (Integer zips) I would understand that there is a variable of class Integer called zips. But the ... are confusing me.
Those are "varargs," syntactic sugar that allows you to invoke the constructor in the following ways:
new Weatherman()
new Weatherman(98115);
new Weatherman(98115, 98072);
new Weatherman(new Integer[0]);
Under the covers the arguments are passed to the constructor as an array, but you do not need to construct an array to invoke it.
That’s a “vararg”. It can handle any number of Integer arguments, i.e.
new Weatherman(1);
is just as valid as
new Weatherman();
or
new Weatherman(1, 7, 12);
Within the method you access the parameters as an Integer array.
You are seeing the varargs feature of Java, available since Java 1.5.
zips is an array of Integer inside the constructor, but the constructor can be called with a variable number of arguments.
From the Java tutorials:
You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually (the previous method could have used varargs rather than an array).
To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.
public Polygon polygonFrom(Point... corners) {
int numberOfSides = corners.length;
double squareOfSide1, lengthOfSide1;
squareOfSide1 = (corners[1].x - corners[0].x)*(corners[1].x - corners[0].x)
+ (corners[1].y - corners[0].y)*(corners[1].y - corners[0].y) ;
lengthOfSide1 = Math.sqrt(squareOfSide1);
// more method body code follows that creates
// and returns a polygon connecting the Points
}
You can see that, inside the method, corners is treated like an array. The method can be called either with an array or with a sequence of arguments. The code in the method body will treat the parameter as an array in either case.
If I remember good it is used when there is a variable number of parameters