Questions tagged [method-reference]
Method references, introduced in Java 8, are a way to refer to a method by its name instead of using a lambda expression.
537
questions
2
votes
1
answer
59
views
Java Generics: Static method of a specific argument Type does not match the Functional Interface
The first assignment below doesn't compile, but I am not sure why, the method signature of the static method matches the functional method signature albeit it is not using type arguments. The second ...
0
votes
0
answers
35
views
Alternatives to cyclic references in Java design [closed]
I am currently working on a design that is quite processing-intensive, and processing happens in various phases which are also required to interact with each other. I have developed various ...
0
votes
2
answers
53
views
How can I use Java 11 repeat() method in a Method reference?
public class X{
public static void print(Integer n, Function<Integer, String> fn) {
System.out.println(fn.apply(n));
}
public static void main(String []args){
print(...
0
votes
1
answer
40
views
Does Java Method Reference has special treatment to a method whose first argument is the same type of the class being referenced? [duplicate]
I have come across a use of Java Method Reference which I don't know how it can be compiled and executed successfully.
I have the following @FunctionalInterface:
@FunctionalInterface
public interface ...
-2
votes
2
answers
69
views
Why and When should I use Functional Interfaces
Say I am writing a Consumer which prints something on the console. Then why shouldn't I directly use the System.out.println() method instead of creating a Consumer?
Similarly, say I want to return a ...
1
vote
2
answers
98
views
Compilation error while merging two Maps is being issued for Map.Entry::getKey
Whenever I use Map.Entry::getKey in my streams for my public methods, I get an issue around my method not being static. I even tried making my method static, and it didn't work.
Below is the compile ...
0
votes
2
answers
62
views
Using method references as listeners with observer pattern
the usage of method references as listeners in an observer pattern does not work.
Example:
public class ObserverWithMethodReferenceAsListenerTest {
class ListenerCurator {
private ...
0
votes
1
answer
63
views
Java HashMap computeIfAbsent Illegal Capacity [duplicate]
I have a hashMap with an arrayList as its value. I would like to use the computeIfAbsent method to efficiently create the list when a key is not in the map. Then I tried to use ArrayList::new instead ...
0
votes
1
answer
26
views
why ModelMapper takes mapping via method reference?
@Bean
public ModelMapper modelMapper() {
ModelMapper m = new ModelMapper();
TypeMap<BatchDTO, Batch> typeMap = m.typeMap(BatchDTO.class, Batch.class);
typeMap.addMappings(mapper ->...
2
votes
1
answer
87
views
Conditions for Method Reference Expression to be "exact"
Consider the following article from the JLS (§15.13.1)
A method reference expression ending with Identifier is exact if it satisfies all of the following:
If the method reference expression has the ...
0
votes
0
answers
55
views
Is method reference guaranteed to evaluate to the same object? [duplicate]
class A {
void b() {}
}
A a = new A();
Runnable c = a::b;
Will c be the same object every time it's initialized?
1
vote
1
answer
28
views
Reduction procedure for MethodReference Expressions
Consider the following article from JLS that describes the reduction procedure for the MethodReference expressions during Type Inference process-:
A constraint formula of the form ‹MethodReference → ...
1
vote
1
answer
66
views
Java 8 method reference usage example
I am going through an example which pulls an Array of hidden files from current directory related to method reference which is as mentioned below
using Anonymous inner class implementation
File[]...
1
vote
1
answer
77
views
How do method references work with threads? `new Thread(foo::bar)`
i just try to create thread by using method reference.
new Thread(thisMonitor::method1).start();
so how to explain why it works.
does it works just like the lambda ?
4
votes
3
answers
119
views
is the type of System.out.println functional interface?
I do not understand one thing, should not the type of the method reference be a functional interface? So how do we pass System.out::println as a parameter to forEach?in the following code :
1-is ...
0
votes
2
answers
62
views
Java method referance complains about class not being functional interface
I have got two cases of method referance:
Case 1:
public class Main {
static List<Person> personList = List.of(
new Person("Daria", 27, List.of(new Book("Potop&...
4
votes
2
answers
123
views
Java Lambda Expressions and Method References to Generic Methods [duplicate]
I have a functional interface
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
@FunctionalInterface
public interface SubmitterCompletable extends Submitter {
@...
2
votes
2
answers
81
views
What does "providing a delegate" mean in the context of a lambda expression?
I have a definition of the :: operator in Java as:
The double colon (::) operator, i.e. method reference operator, is
used to call a method by referring to it with the help of its class
directly. ...
0
votes
0
answers
23
views
Different return value inferred for MethodReference java
I am stuck to infer the error for this code invocation.
This is a method with return type as Supplier<Stream<Integer>>
private static Supplier<Stream<Integer>> ...
-1
votes
1
answer
54
views
Calling method reference using lambda (:: operator)
I have seen some approaches as shown below:
calling like this:
private static void addCustomerTransaction() {
customerInput((bank, branchName, customerName, transaction) ->
bank....
0
votes
4
answers
179
views
Why this method is ambiguous?
I have two polymorphic methods that take two types of classes as input.
I would like the stream based on the object to do two different actions.
Instead he tells me that the method is ambiguous.
Not ...
1
vote
0
answers
158
views
Mocking a Lambda Argument with Mockito unable to find right ArgumentMatcher
I've a code where I pass a lambda as a RowMapper to a framework class, which use this lambda to trigger a org.springframework.jdbc.core.JdbcTemplate.query(...) method.
As this is Lambda and not a ...
3
votes
1
answer
75
views
Java: Does lambda and method reference have different execution timing? [duplicate]
Code:
@FunctionalInterface
interface VoidSupplier {
void apply() throws Exception;
}
void execute(VoidSupplier voidSupplier) {
if (voidSupplier != null) {
try {
...
0
votes
0
answers
45
views
How does key extraction work with the Java Comparator.comparing() method?
The Java API specifies the following for the comparing() method in the Comparator<T> interface:
static <T,U extends Comparable<? super U>> Comparator<T> comparing (Function<...
0
votes
1
answer
270
views
Does Java Integer class have a compare method which returns Comparator?
I was reading the Java tutorial and saw this line of code:
Comparator<Integer> normal = Integer::compare;
About the right hand side, I tried looking for documentation which explains how compare ...
1
vote
1
answer
40
views
Object creating and invoking using method reference
I wanted to understand :: operator a bit more, and with this intention, created a sample program:
public class Second {
public static void main(String[] args) {
doWork(new int[] { 1, -1,...
1
vote
1
answer
94
views
Java Stream - use subsequent map with method references, or single map with lambda? [duplicate]
What is the better practice for mapping objects in Stream API?
class SomeObject{
}
class SomeComplexObject {
private SomeObject someObject;
public SomeObject getSomeObject() {
return ...
1
vote
1
answer
52
views
Pass method reference from different subclasses
I'm currently stuck figuring out how method references works. This is what I'm trying to achieve.
User user = new User(...);
user.getValue(ADerived::getPropertyFromA);
user.getValue(BDerived::...
0
votes
0
answers
41
views
How to assign a method as an attribute to use it later on any compatible object?
I am trying to create a generic menu over an arbitrary type T implementing a Menuable interface:
public interface Procedure {
void invoke();
}
public class Menu<T extends Menuable> ...
2
votes
1
answer
49
views
Issue in understanding the working of Method Referencing
I am trying to understand the working of Method Reference:
Note: I did go through the link :: (double colon) operator in Java 8 and fw other related articles.
I am trying to call addMoney() method ...
1
vote
1
answer
184
views
Confused with using method reference in Comparator.comparing() [duplicate]
Am a self learning developer, now learning Java. I have learned that to use method reference for a Functional Interface, the signature of the method we referring must match the signature of the ...
0
votes
0
answers
61
views
How can a Java Predicate<T> allow a method without argument? [duplicate]
From what I have studied, Predicate is a functional interface that has an abstract method boolean test(T var1);. So if I use the method reference of Java 8 and pass it to a function ...
0
votes
2
answers
65
views
How Java treat method reference of instance methods? [duplicate]
I'm reading Oracle's Java SE tutorial on method reference and I came across the problem of method reference's mechanism of parsing instance methods.
In the tutorial, there's a snippet using method ...
0
votes
2
answers
42
views
Graphics2D and GUI: ArrayList of methods, method reference error
Imagining I have an arrayList of three JButtons: b_line, b_rect, b_oval, whose functionalities are very similar - they draw line/rectangle/oval on the JFrame.
Instead of writing actionListener for all ...
0
votes
2
answers
64
views
Method references on instances - why not call method directly (because how can it execute in a different context)?
I am trying to understand this example code from Oracle Learning on Lambdas and Method References:
String city = "Munich";
Supplier<String> lambda = city::toUpperCase;
System.out....
-1
votes
1
answer
37
views
How a Method Reference to an instance method is working without new() in this example?
In Collectors.groupingBy(Student::getGrade,....); getGrade() method is used without new keyword. Method getGrade is not a static method. How it is working without new
class TestClass {
public ...
1
vote
3
answers
103
views
Reference to method with .apply
I have a List called "racers" of simple class
class Racer {
private String name;
private String teamName;
// and getters
}
I am using а method to find maximum lengths of the ...
2
votes
1
answer
122
views
Why function composing not available in IntFunction
I was reading the function composition section from Chap-3 Modern Java in action.
I am unable to understand why I can't compose IntFunctions. Am I making a silly mistake or is there any design ...
5
votes
3
answers
310
views
Method reference for static and instance methods
I am unable to grasp the concept of Method references in case of instance methods in Java
For example in the example below, the compiler is giving error in the list line.
I have seen the examples of ...
-1
votes
2
answers
381
views
Method references not working in Java stream filter
I have a list with some strings and I want to filter these list, but the methode reference ::startsWith is not working as I expect it.
private static final String KEY = "key=";
List<...
4
votes
1
answer
49
views
How to use lambdas together with functional interfaces and directly assign lambda to var in kotlin
I have this code:
package org.medianik.kotlindoc
fun main(){
val creator:Creatable = toCreatable(::Created)// Ok. Compiles, and works fine
val creator1:Creatable = ::Created // Compilation ...
2
votes
1
answer
203
views
How to inspect java method references (double colon) operator usages in classes during build time
Is there a way to detect usages of java method reference (double colon) operator inside the code?
I need to discover all instance/static method references used in a given class in order to be able to ...
0
votes
3
answers
1k
views
Java, method reference - how to print the list values [duplicate]
I have the following list. I'd like to print the values using lambda and method reference.
The first lambda expression works, but I have no idea how to print the values using the method reference, ...
1
vote
1
answer
110
views
Error in assigning unbound method reference
Below code is compiling successfully where I am assigning bound method reference to functional interface.
Consumer<String> con = System.out::println;
But below code where I am assigning unbound ...
0
votes
0
answers
54
views
Method Reference using pre defined functional interfaces [duplicate]
I am trying out few things related to method references using functional interfaces. I wanted to convert a string into the upper case using a bounded receiver and an unbounded receiver.
Although I ...
2
votes
1
answer
191
views
Playing with Strategy Design Pattern using lambda expression by following Venkat Subramaniam's book?
I'm following book from professor Subramaniam. In the book professor is trying to explain principle of Delegating Using Lambda Expressions.
We used lambda expressions and the strategy pattern to ...
0
votes
1
answer
45
views
Compile error for method reference in multiple exception handling
There is an interesting situation I have encountered. I have 2 exception classes MyException1 and MyException2. During multiple catch(MyException1 | MyException2 ex) SonarLint suggests using method ...
0
votes
1
answer
132
views
Java. How to prevent assigning a method reference to functional interface type argument?
Beginning with Java SE 8, if the formal parameter of a method is a functional interface, the argument can be either an object implementing that interface or a reference to some method. It means that ...
2
votes
3
answers
437
views
How to declare method reference in groovy?
Im trying to use method reference in groovy. And I could not get it working.
The following is working in groovy.
Option2> list.stream().map(user -> user.getName()).collect(Collectors.toList())
...
0
votes
0
answers
26
views
Visual Studio 2019 Community Edition method references not displayed in Editor [duplicate]
There is no option of references above the method, property, or any declaration in Visual Studio 2019 Community Edition.
If this option available in Visual Studio 2019 Community Edition then please ...