4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Java】メソッド参照とコンストラクタ参照

Posted at

メソッド参照とは

すでに定義済みのメソッドを、引数なしで呼び出せるのがメソッド参照です。
これを使うと、ラムダ式を書かずに直接メソッドを実行できる、などのメリットがあります。

class Person {
    private final String firstName;
    private final String lastName;

    public Person(String firstName, String lastName){
        this.name = firstName;
        this.surname = lastName;
    }

    public String getName(){ return firstName; }
    public String getSurname(){ return lastName; }
}

List<Person> people = getSomePeople();

メソッド参照

people.stream().map(Person::getFirstName)

ラムダ式で書いた場合

people.stream().map(person -> person.getFirstName())

静的メソッド

以下は Integer を String に変換しています

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.stream().map(String::valueOf)

ラムダ式で書いた場合

numbers.stream().map(num -> String.valueOf(num))

コンストラクタ参照

以下は String を Integer に変換しています

List<String> strings = Arrays.asList("1", "2", "3");
strings.stream().map(Integer::new)

ラムダ式で書いた場合

strings.stream().map(s -> new Integer(s));

#参照
Javaメソッド参照・コンストラクター参照

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?