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.

Method references were introduced in alongside lambda expressions.

The programmer can use a method reference as a syntactic sugar for a lambda expression that would merely call that method, when its signature is compatible with the type.

The syntax of a method reference closely matches a method invocation expression, but with a double colon (::) replacing the dot (.).

// static method reference:
ToIntFunction<String> parseInt = Integer::parseInt;
int i = parseInt.applyAsInt("123");

// instance method reference:
Consumer<Object> println = System.out::println;
println.accept("Hello world!");

// constructor method reference:
Supplier<Object> newObject = Object::new;
Object o = newObject.get();

// array creation method reference:
IntFunction<Number[]> newArray = Number[]::new;
Number[] a = newArray.apply(10);

When working with generics, type arguments may be provided explicitly or inferred.

Supplier<List<String>> listSupplier;

// explicit type argument for a class:
listSupplier = ArrayList<String>::new;
// inferred type argument for a class:
listSupplier = LinkedList::new;
//             ^^^^^^^^^^
//             note: not a raw type in this context!
//             LinkedList<String> will be inferred.

// explicit type argument for a method:
listSupplier = Collections::<String>emptyList;
// inferred type argument for a method:
listSupplier = Collections::emptyList;

See also:

567 questions
0
votes
0 answers

Method reference: pass containing object type as generic parameter

I am trying to design my class using generics. The following code compiles and works well: public class Main { static class TestDataProvider { public String getString(){ return "Data provider. Test String"; } public int…
Yury Rudakou
  • 411
  • 3
  • 15
0
votes
1 answer

Why doesn't type inference work the same on lambdas and method references in Java?

The code should not compile but it does! public class MyClass { ........... private void setEndDateOfValidStatusToCurrentTime(List oldStatuses, Date currentTime) { oldStatuses.stream() .filter(oldStatus…
softwarelover
  • 1,009
  • 1
  • 10
  • 22
0
votes
0 answers

Lambda doesn't translate into Method Reference

Android Studio informs me that the following Lambda can be converted into a Method Reference: result -> result.getBleDevice() But when I try, I get an error: RxBleScanResult::getBleDevice The result parameter is of type…
Robert Lewis
  • 1,847
  • 2
  • 18
  • 43
0
votes
1 answer

Method Reference to private constructor throws IllegalAccessError

Edit: Thanks for the commenters trying to repro! It's starting to look like this is an issue with Dexguard specifically. this may be related to DexGuard integration in Android Studio 3.0. So I'm running into an odd error when trying to pass a…
0
votes
2 answers

Is it possible in Java 8 to define/implement methods using method references?

Is there any way to define methods via method references, as demonstrated by the following imaginary code (and imaginary syntax)? class A { public Sometype somefunction(Argtype arg) { ... return somevalue; ..} } class B { public…
0
votes
0 answers

Can you use a method reference to define a class implementing a Functional interface in java 8

So we know that Java 8 method references can be used to replace anonymous class creation. I'm curious if there's a way to use them to define named classes that implement a functional interface, something -- vaguely -- along the lines of public…
anqit
  • 780
  • 3
  • 12
0
votes
0 answers

How does unboxing and auto boxing occur when a method reference is passed for a generic method?

Here is a piece of code: @FunctionalInterface interface NumericFunc{ int fact(T[] a,T b); } class MyStringOps{ static int counter(T[] a,T b){ int count=0; for(int i=0;i
0
votes
1 answer

Constructor reference incorrecty marked as error in IntelliJ 2017.1.4

EDIT: As of IntelliJ version 2017.2 this issue has been fixed. Java version: 1.8.0_131 IntelliJ IDEA version: 2017.1.4 I have this class: public class MethodReferenceWithArguments { static T createWith(Function
fps
  • 33,623
  • 8
  • 55
  • 110
0
votes
1 answer

How to change lambda expression to method reference

I need help regarding changing lambda expression to method reference: lambda expression: intervalCodes.stream().forEach(code -> { modProfile.addIntervalUsageCode(createIntervalCode(code)); }); Can I change the above expression…
mrs
  • 207
  • 2
  • 5
  • 13
0
votes
3 answers

Java 8: Do not understand the way Java implements Functional Interfaces

lets say we a Predicate and a Function-Interface: Function function = null; Predicate predicate = null; Now I want to give the Predicate-Interface a method reference where the return type is a boolean and in our case the…
user3133542
  • 1,695
  • 4
  • 21
  • 42
0
votes
1 answer

Java 8 BiPredicate automatically calling method on first argument?

I have the following code: public class BiPredicateTest { public static void main(String[] args) { BiPredicate, Integer> listContains = List::contains; List aList = Arrays.asList(10, 20, 30); …
Ali
  • 1,442
  • 1
  • 15
  • 29
0
votes
1 answer

Get method reference from class object in JAVA 8

I have class names unknown to my factory class that I obtained via runtime input. Currently I have solution to use reflection to create instances of these classes in my factory class, but I want to see if it is possible to pass the method reference…
user1589188
  • 5,316
  • 17
  • 67
  • 130
0
votes
0 answers

Is it possible to apply instance method reference to a different object that the reference source?

As far as my understanding goes, method references can be used either statically or with wrapped object instance, for example: public class MethodReferencesExampleTest { class Example { private String variable; public…
Jezor
  • 3,253
  • 2
  • 19
  • 43
0
votes
1 answer

Understanding method reference with newly created instance

I completely understand this form: Set set = new HashSet<>(); list.stream().allMatch(t -> set.add(t)); // And that list.stream().allMatch(set::add); But this ad-hoc instance really confuses me: list.stream().allMatch(new HashSet<>()::add); The…
user and
  • 550
  • 4
  • 9
0
votes
2 answers

Method Reference Using An Interface (Implemented By More Than One Class) As A Type

public interface Intf { int size(); } public class Cls1 implements Intf { public int size() { // implementation 1 } public class Cls2 implements Intf { public int size() { // implementation 2 } Now, which of the above two implementations will the…
user6907041