Extraire uniquement des éléments spécifiques des objets de la liste
Flux Java 8
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]
Si vous supprimez le commentaire "distinct" [Taro, Jiro, Hanako]
Le point de compréhension de l'expression lambda / API Stream est "type" Maîtriser le flux Java 8