【Java】map(stream)で欲しいフィールドを取得しよう!

「あるリスト型オブジェクトの特定のフィールドのみ取得したい!」そんな時ありますよね!

そんな時は、streamでブン回してmapせよです!( ゚Д゚)

さあ見ていきましょう

// こちらはコンテナ!!
public class Hoge {
	private Integer id;
	private String name;
	private String age;
	private Integer organizationId;

	public Hoge(Integer id,
			String name,
			String age,
			Integer organizationId) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.organizationId = organizationId;
	}
}

上のオブジェクトのリスト(hogeList)を生成します!

List<Hoge> hogeList = new ArrayList<>();
Hoge hoge1 = new Hoge(1, "愛","20", 1000);
Hoge hoge2 = new Hoge(2, "海","21", 1001);
Hoge hoge3 = new Hoge(3, "佐賀","23", 1002);
Hoge hoge4 = new Hoge(4, "田坂","20", 1003);
Hoge hoge5 = new Hoge(5, "奈良","21", 1004);

hogeList.addAll(
		Arrays.asList(hoge1, hoge2,hoge3,hoge4,hoge5));

さあここからがmapの活躍の場です!

「hogeList」から「組織ID(organizationId)のリスト」を生成します!

// 組織IDのリストが完成
List<Integer> organizationIdList = 
				testDtoList.stream()
				.map(TestDto::getOrganizationId).collect(Collectors.toList());

今回の場合、「.map(型::getフィールド変数)」で取りたいフィールド変数が取得できるのだ

最後にはもちろんリストにしてあげないといけないので、「.collect(Collectors.toList())」は忘れずに!

ではっ

是非フォローしてください

最新の情報をお伝えします

コメントを残す