593 questions
3
votes
3
answers
137
views
Why must my method take an ActionEvent when using this::methodName with addActionListener?
I’m working on a simple Swing GUI in Java and have a method addListeners() where I attach an ActionListener to a button like this:
increase.addActionListener(this::increasePoints);
However, this line ...
1
vote
2
answers
64
views
Angular reference issue when functions are passed as input to child
I am trying to build a data-grid library by wrapping ag-grid, so that if client decides to change ag-grid to some other library we dont have to work on multiple pages on refactoring. We can just make ...
0
votes
1
answer
105
views
Multiple print statements without null checks using Optional [duplicate]
I am trying to convert the below null check of legacy java 7 code to modern java using Streams and Optional.
if (person != null) {
System.out.println(person.getName());
System.out.println(person....
1
vote
2
answers
121
views
Static method reference in an anonymous class
Consider the following contrived "hello, world":
abstract public class Main implements java.util.function.Supplier<Runnable> {
public static void main(String[] args) {
new ...
0
votes
2
answers
187
views
Understanding the difference between two Thread implementation approaches in Java?
I'm learning about Java Threads and I've encountered two different ways to create a thread. I'm not sure about the technical differences between them:
// Approach 1
Thread n = new Thread(new ...
2
votes
2
answers
117
views
How to specify a method reference sequence?
I've been trying to hack a bit around this very ugly looking piece of code in my codebase.
The original code looks like this:
Long variable = Optional.of(message)
.map(Message::getPayload)
....
-2
votes
1
answer
102
views
Stream anyMatch accept an method reference not implement Predicate [duplicate]
Stream.anyMatch is defined as:
boolean anyMatch(Predicate<? super T> predicate)
I created a new Class as follows:
class ClassA {
public boolean anyMethodName(Object o) {
return ...
12
votes
1
answer
684
views
Ambiguity in method references
Consider the following snippet:
public static void main(String[] args) {
Function<String, String> function = String::toUpperCase; //OK
// Comparator<String> ...
2
votes
1
answer
111
views
Groovy3: how to get "Java lambdas" instead of closures?
I did some tests in Groovy3 and Java lambda expressions are mostly interpreted as closures instead of as Functional Interface instances.
How can I make lambdas work with Generics in a practical way (...
0
votes
1
answer
405
views
Method reference and type inference in java 8
I'm facing issue with method reference and type inference.
Parent class that returns T type :
public class Parent {
public <T extends Parent> T get() {
...
}
}
The following ...
0
votes
0
answers
38
views
Java lambdas/method references used as callbacks in addCallback/removeCallback style methods
I've read about this but I haven't found a clear answer.
Assume an API like the following:
Callback callback = new Callback();
myApi.addCallback(callback);
[...]
myApi.removeCallback(callback);
Now, ...
-1
votes
1
answer
119
views
Why does my lambda expression compile while the equivalent method reference does not? Is generics the problem or am I the problem?
I am trying to use method references with generic classes and have noticed that I can make it work with the equivalent lambda expression, but not with method references. I'm wondering if someone can ...
1
vote
1
answer
301
views
How to access the receiver of a method reference?
I have a method reference (represented by the kotlin.reflect.KFunction0 interface). What I would like to do is to get the receiver object of the method reference.
For example:
data class MyClass(val ...
1
vote
0
answers
57
views
Why does method reference can be used instead of PropertyChangeListener? [duplicate]
In the following Java code, PropertyChangeListener is implemented in two ways: 1) using a class that implements PropertyChangeListener interface, and 2) using a method reference.
According to the API, ...
0
votes
1
answer
81
views
How to remove listener from Clipboard manager when using the method reference operator?
I have started using the method reference operator :: in java.
I am basically adding a Clipboard listener to the clipboard manager like this:
this.clipboardManager.addPrimaryClipChangedListener(...
0
votes
1
answer
123
views
Java error when passing in generic method parameter
public static class MyClass {
public String methodS(UnaryOperator<String> fn) {
return fn.apply("");
}
public Integer methodI(UnaryOperator<Integer> fn) {
...
0
votes
0
answers
132
views
Problem with Method reference operator and CompileStatic
In the following code, @CompileStatic does not work in combination with the method reference operator for Groovy methods collect and find, although it works with Java streams or the method pointer ...
1
vote
3
answers
434
views
C++ equivalent of Java's method references?
I have a std::vector<std::vector<int>>, from which I want to check whether there is at least 1 sub-vector that's empty. So I have this:
std::any_of(vec.begin(), vec.end(), [](const auto&...
-3
votes
1
answer
262
views
code smell sonar Replace this lambda with a method reference
Sonar is throwing code smell at the below lines:
File file = new File(xxxxxx);
Arrays.stream(file.listFiles()).map(path->path.getName()).collect(Collectors.toList()).toString();
I already ...
0
votes
1
answer
63
views
what is the the natural expression of this Lambda expression and method reference in the method usage or it just don't have it?
public static void main(String[] args) {
Student[] students = new Student[4];
students[0] = new Student("guy1", 103, 334); // height / age (randomly written)
students[...
0
votes
0
answers
92
views
return method reference of object that created inside the method
i'm trying to understand some scenario i ran into related to method-reference. i have a method that create an object and then return a method reference based on that object. when the function ends, ...
0
votes
3
answers
315
views
Interface method reference to a functional interface
I am working with Java Spring framework and JWT - Java Web Tokens. I have below class
import java.util.function.Function;
import org.springframework.security.core.userdetails.User;
import org....
1
vote
1
answer
141
views
java 8 method reference calling non static method in a static way [duplicate]
I am learning method references in Java 8. I learnt that we can define functional interface method with either lambda or method reference.
Method reference is a way of telling "there exist a ...
0
votes
0
answers
23
views
Method reference of method throwing checked exception triggers compilation error at point method reference is named [duplicate]
I have a bunch of methods, with similar signatures, compatible with Function, they each declare throws InterruptedException, and I put them in a list and select one by its index and call its apply().
...
-1
votes
1
answer
120
views
Why i cant use StringBuilder::reverse in as method reference to reverse a string?
Why i cant use StringBuilder::reverse in as method reference to reverse a string?
please help make me understand whats going on under the hood.
import java.util.ArrayList;
import java.util.Arrays;
...
3
votes
2
answers
153
views
Function::apply when BiFunction<T, U, R> is required
I am confused about the following line:
Seq<String> s1 = seq.zip(split, Function::apply);
In this snippet:
static String underscoreToCamel(String str) {
UnaryOperator<String> ...
1
vote
2
answers
562
views
Assigning method references to Functional Interfaces
Java 8+ allows assigning method references to Functional Interfaces.
Then what is the problem with below code (jdoodle link) -
public void newMethod(){
Predicate p = String::isBlank;
}
...
1
vote
2
answers
173
views
How is Double::isFinite different from Double::isInfinite?
I have the following code:
class Result {
public Result(long infiniteCount, DoubleSummaryStatistics statistics) {
this.infiniteCount = infiniteCount;
this.statistics = statistics;
...
-1
votes
1
answer
133
views
Compilation error at .collect(Collectors.toList(ArrayList<int[]>::new)) when collecting a stream to an ArrayList
IntStream.iterate(0, i -> i + chunkSize)
.limit((long) Math.ceil((double) input.length / chunkSize))
.mapToObj(j -> Arrays.copyOfRange(input, j, j + chunkSize > input....
-1
votes
2
answers
217
views
List of non-static method references in Java
I am trying to use a list of function references as a lookup table (avoiding the need for a long switch statement). The code worked for a list of static methods, but when I tried to use non-static (i....
0
votes
1
answer
47
views
Make multiple Java streams assign values more compact [duplicate]
I have similar lines of code
batchPrice1 = items.stream()
.map(CommodityItem::getTotalPrice1)
.reduce(ZERO, BigDecimal::add);
batchPrice2 = items.stream()
...
0
votes
1
answer
494
views
Group elements by nested field
I have the following domain classes:
public class Task {
private Project project;
}
public class Project{
private int id;
}
And I have a list of tasks called tasks.
I would like to group ...
3
votes
2
answers
604
views
Use property getter method reference for functional (SAM) interface variables
I want to pass a property getter method reference as one of the function arguments, and have that argument be of my own functional interface type, but ran into an issue.
Here's a stripped down minimal ...
-4
votes
1
answer
96
views
Return type mismatch and Java compiles
I am curious as to how the below code compiles
@Bean(name = "ErrorDecoder")
public ErrorDecoder streamHubErrorDecoder() {
return FeignException::errorStatus;
}
The type of ErrorDecoder ...
3
votes
2
answers
771
views
How can a parameterless method toUpperCase() implement Function.apply()? [duplicate]
I'm learning Java 8 with Lambda, Streams, and method reference. Regarding the example below,
Optional<String> s = Optional.of("test");
System.out.println(s.map(String::toUpperCase).get(...
1
vote
1
answer
101
views
Abstracting repeated Intermediate Stream-operations into a single Function
I am working with a large data structure where I want to perform a series of stream operations of the pattern:
<some stream>
.map(<method reference getter that returns List>).filter(...
-1
votes
1
answer
288
views
How to use a Function<T, R> as parameter in method
I'm learning Java lambdas for school, and I am stuck for a couple of days now.
Background
I have a list of pumps which I have to sort out on power, last revision, …
I already wrote a Comparator that's ...
-2
votes
1
answer
302
views
Why is the double colon operator needed in Java? [duplicate]
I'm coming from a JavaScript background and I'm seeing the :: operator for the first time. I understand what it does, but I'm wondering why it's necessary. In JavaScript, something like this is ...
4
votes
1
answer
481
views
method in class String cannot be applied to given types when replacing lambda with method reference in JDK 11
I'm facing an odd issue
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.Function;
import java....
0
votes
0
answers
67
views
Visual Studio Codelens for methods invoked by reflection
Codelens in Visual Studio is great, but I've inherited a code base where some methods are invoked via reflection.
This is a simplified sample.
...
if (method.Name.EndsWith("UpdatePlatformModel&...
0
votes
1
answer
742
views
How to call lambda from Enum constructor
I'm trying to set up a enum where each Enum value has a custom method to be called. However, it tells me that the method must be static. Is there a way to reference a non-static method?
My code ...
1
vote
3
answers
463
views
How do i handle or log exception for Method references?
I have the code snippet below. But i was wondering how to try catch exception with method references. I want to write try catch block for getUserByUserId method, probably log it and catch with ...
1
vote
0
answers
236
views
Java compiler gets confused when passing overloaded method reference to an overloaded method
I'm encountering some weird behavior when passing overloaded method references to a method overloaded with a Function and Supplier variant:
public class OverloadedMethodReferenceToOverloadedMethod<...
0
votes
1
answer
54
views
How to reference a method in EL which does not meet naming convention
Java List type does not have a getSize() method. Is there a way to tell reference the size() method in EL instead? I've tried #{aList.size > 10} but that is not working.
1
vote
1
answer
173
views
Method reference notation vs "standard" Lambda notation
I was expecting these to be simple drop-in replacements for each other, but they're not. Clearly I'm not understanding the notation.
Can anyone explain why does that happen?
playButton.setOnAction(e -&...
2
votes
1
answer
80
views
How do lambda and double colons differ when method references are used as input parameters to KeyBy?
Flink version is 1.10.0
codes as follow:
public class WorkerOnlineStatusRun {
private static String datahubEndpoint = GlobalParameter.getPublicEndpoint();
private static String redisServer = ...
0
votes
2
answers
75
views
Restrict method reference parameter type
Set<String> premiumStrings = new HashSet<>();
Set<String> sortedSet = new TreeSet<>(Comparator.comparing(premiumStrings::contains).thenComparing(Comparator.naturalOrder()));
...
1
vote
1
answer
419
views
Unresolved reference after changing lambda to method reference
In the following example (also on Kotlin Playground), IntelliJ offers to change the lambda (as in the commented-out first line of main) to a method reference (as shown in the second line of main).
fun ...
-1
votes
1
answer
148
views
How Inheritance works in Java with method reference operator
Interface
public interface InterfaceOne {
void start();
void stop();
}
Main Class
public class MainProg {
public static void main(String [] args){
new ServiceA().start();
}
}
...
2
votes
1
answer
175
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 ...