12
11

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.

オブジェクトのリストから特定の要素を抜き出す

Posted at

目的

リスト内のオブジェクトから特定の要素だけを抜き出す

手段

Java8のStream

サンプル

オブジェクト

NamePlate.java
package stream;

public class NamePlate {
	private Integer id;
	private String name;

	public NamePlate(Integer id, String name) {
		this.id = id;
		this.name = name;
	}

	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

目的の処理

StreamSample.java
package stream;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamSample {
	public static void main(String[] args) {
		List<NamePlate> source = Arrays.asList(
				new NamePlate(1, "Taro")
				, new NamePlate(2, "Jiro")
				, new NamePlate(3, "Hanako")
				, new NamePlate(4, "Jiro")
				, new NamePlate(5, "Jiro")
				, new NamePlate(6, "Taro")
				);

		List<String> nameList = source.stream()
				.map(s -> s.getName())
				//.distinct()
				.collect(Collectors.toList());

		System.out.println(nameList);
	}
}

結果

[Taro, Jiro, Hanako, Jiro, Jiro, Taro]

コメントアウトしている「distinct」をはずすと
[Taro, Jiro, Hanako]

参考

ラムダ式・Stream APIの理解のポイントは「型」
Java8のStreamを使いこなす

12
11
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
12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?