I was told to convert a lambda with a parameterized constructor to a method reference

Suppose I have a class Gizmowith a constructor that takes a string. Suppose I want to convert a List<String>to List<Gizmo>.

I can write:

List<String> strings = new ArrayList<>();
List<Gizmo> gizmos = strings
        .stream()
        .map(str -> new Gizmo(str))
        .collect(Collectors.toList());

Now the problem is that IntelliJ says that I can replace the lambda with a method reference. The fact is that I'm almost sure that method references cannot take parameters.

+4
source share
4 answers

I think InteliJ means replacement

.map(str -> new Gizmo(str))

with

.map(Gizmo::new)

which is a reference to the constructor. Detailed description here .

+9
source

, IntelliJ , .

, :

.map(str -> new Gizmo(str))

:

.map(Gizmo::new)

.

+3

.

- -sugared static/instance (, lambda/clojure), .

- (t -> new Gizmo(t)) ; :

  private static Gizmo lambda$main$0(String s) {
      return new Gizmo(s);   
  }

( ) .

+1

- , : , , . - , .

, Person:

public class Person {

    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age  age;
    }

    // getters, setters
}

, BiFunction<String, Integer, Person>, Person:

BiFunction<String, Integer, Person> personCreator = 
    (String name, Integer age) -> new Person(name, age);

, - :

BiFunction<String, Integer, Person> personCreator = (name, age) -> new Person(name, age);

2-arg :

Person joe = personCreator.apply("Joe", 25);

, (name, age) ? , :

BiFunction<String, Integer, Person> personCreator = Person::new;

, :

Person jane = personCreator.apply("Jane", 23);

This is just to show you that the number of arguments doesn't matter when using method references. All that needs to be matched is the signature of the only abstract method of the functional interface (in this case BiFunction.apply) with the signature of the constructor.

If you want to read method references in more detail, go to the section on method references in the Java tutorial.

0
source

Source: https://habr.com/ru/post/1677403/


All Articles