I have a List<Person>
. I need to get a List
from a property of Person
.
For example, I have a Person
class:
class Person
{
private String name;
private String birthDate;
public String getName() {
return name;
}
public String getBirthDate() {
return birthDate;
}
Person(String name) {
this.name = name;
}
}
List<Person> personList = new ArrayList<>();
personList.add(new Person("David"));
personList.add(new Person("Joe"));
personList.add(new Person("Michel"));
personList.add(new Person("Barak"));
I want to get a list of names with the Stream
API, like this:
List<String> names = personList.stream().somecode().collect(Collectors.toList());
names.stream().forEach(System.out::println);
#David
#Joe
#Michel
#Barak
This code doesn't work:
public class Main
{
public static void main(String[] args)
{
List<Person> personList = new ArrayList<>();
Person person = new Person("????");
person.getFriends().addAll(Arrays.asList("???? 1", "???? 2", "???? 3"));
personList.add(person);
person = new Person("?????");
person.getFriends().addAll(Arrays.asList("???? 4", "???? 5", "???? 6"));
personList.add(person);
person = new Person("???????");
person.getFriends().addAll(Arrays.asList("???? 7", "???? 8", "???? 9"));
personList.add(person);
person = new Person("??????????");
person.getFriends().addAll(Arrays.asList("???? 10", "???? 11", "???? 12"));
List<String> friens = personList.stream().map(e->e.getFriends()).collect(Collectors.toList());
friends.stream().forEach(System.out::println);
//???? 1
//???? 2
//???? 3
//???? 4
//...
}
}
class Person
{
String name;
List<String> friends;
Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public List<String> getFriends() {
return friends;
}
}
How can I get a List
of a property with Stream
API?
This question is related to
java
collections
java-8
java-stream
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
Source: Stackoverflow.com