Extract only specific elements from objects in the list
Java 8 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]
If you remove the commented out "distinct" [Taro, Jiro, Hanako]
The point of understanding lambda expressions and Stream API is "type" Mastering Java 8 Stream
Recommended Posts