0

I have a class Person which has the field String name. In another class I have a list of Persons. Is it possible to get a list of the person's names using the Java 8 streaming API?

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
user1406177
  • 1,328
  • 2
  • 22
  • 36

2 Answers2

2

You can try this, using Stream:

personList.stream().map(p -> p.getName()).collect(Collectors.toList())
arshajii
  • 127,459
  • 24
  • 238
  • 287
  • Or, instead of `p -> p.getName()`, you could use a method reference `Person::getName`. It might be a bit more readable. – Stuart Marks Apr 26 '14 at 00:01
0

From http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#approach9

yourCollection
.stream().map(p -> p.getName())//here you have stream of names

now all you have to do is convert this stream to list

.collect(Collectors.toList());

So try

List<String> names = yourCollection
                     .stream()
                     .map(p -> p.getName())
                     .collect(Collectors.toList());
Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269