31
30

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 5 years have passed since last update.

Java8を使い始めてよく書いたラムダ式

Posted at

10月末からJava8を使い始めたのでよく書いた/レビューしたラムダ式をまとめる。他にもあったかもしれない

ラムダ対象にするクラス

MasterData.java
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Date;

@Data
@AllArgsConstructor
class MasterData {
    private int id;
    private String name;
    private Date start;
    private Date end;
    private int sort;
}

条件でフィルタ

long now = new Date().getTime();
List<MasterData> filtered = list.stream()
        .filter(masterData -> masterData.getEnd().getTime() > now)
        .collect(Collectors.toList());

最初の1件取得

MasterData findOne = list.stream()
        .filter(masterData -> masterData.getId() % 2 == 0)
        .findFirst().get();

ソート

List<MasterData> sorted = list.stream()
        .sorted(Comparator.comparing(MasterData::getSort))
        .collect(Collectors.toList());

特定のプロパティだけ抜き取る

List<String> names = list.stream()
        .map(MasterData::getName)
        .collect(Collectors.toList());

最大を求める

MasterData max = list.stream()
        .max(Comparator.comparing(MasterData::getSort))
        .get();
31
30
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
31
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?