2
0

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 1 year has passed since last update.

【Java】今更知ったAtomicIntegerでラムダ式内処理結果をカウント

Posted at

以下のように実装できます。

AtomicInteger successCount = new AtomicInteger(0);
// 何かしらのデータ取得処理
List<ClassA> dataList = getDataList();
dataList.stream().forEach(data -> {
    try {
        // 何かしらの処理
        process(data);
        successCount.incrementAndGet();
    } catch (Exception e) {
        throw e;
    }
});

ラムダ式を使うとローカル変数のインクリメントによるカウントができないため、
非常にダサいですが元々は以下のように成功するたびにListにtrueを追加して、その数をカウントしていました。

List<Boolean> successList = new ArrayList<>();
// 何かしらのデータ取得処理
List<ClassA> dataList = getDataList();
dataList.stream().forEach(data -> {
    try {
        // 何かしらの処理
        process(data);
        successList.add(true);
    } catch (Exception e) {
        throw e;
    }
});
2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?