LoginSignup
9
7

More than 5 years have passed since last update.

ラムダ式や無名クラスのメソッドから、外部に値を渡す方法

Posted at
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceSample {
    public static void main(String[] args) {
        Optional<String> opt = Optional.of("test");

        final AtomicReference<String> upperCase = new AtomicReference<>();
        final AtomicInteger length = new AtomicInteger();
        opt.ifPresent(s -> {
            upperCase.set(s.toUpperCase());
            length.set(s.length());
        });

        System.out.println("upper case: " + upperCase.get());
        System.out.println("length: " + length.get());

    }
}

ラムダ式に値を渡すにはfinalで宣言する必要があるため、ラムダ式内で生成した値をラムダ式外で取得するには、通常は戻り値を利用する。しかし複数の値を取得したい場合や戻り値の型に制約がある場合は別の方法で値を受け渡す必要がある。

ラムダ式外で値を入れるための箱(AtomicReferenceなど)を用意し、ラムダ式内でその箱に値を入れることで解決できた。

9
7
1

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
9
7