Hey everyone! I’m trying to get my head around the Stream API in Java 8. I want to make a simple list of strings from a property in my objects. Here’s what I’ve got so far:
class Person {
String firstName;
int yearOfBirth;
}
List<Person> peopleList = dataProvider.getPersons();
List<String> nameList = peopleList.stream().map(person -> person.firstName).collect(Collectors.toList());
But it’s not working right. The compiler is throwing a fit. Any ideas what I’m doing wrong here? I thought this would be straightforward, but I guess I’m missing something. Thanks for any help!
Your code is quite close to being correct. The issue likely stems from direct field access. In Java, it’s generally better to use getter methods for encapsulation. Modify your Person class to include a getFirstName() method:
class Person {
private String firstName;
private int yearOfBirth;
public String getFirstName() {
return firstName;
}
}
I’ve been working with the Stream API a lot lately, and I can tell you it’s a game-changer once you get the hang of it. Your approach is spot-on, but there’s a small hiccup with accessing the firstName directly. Here’s what I’ve found works best:
Make sure your Person class has a getter for firstName. Then, your stream operation should look like this:
List nameList = peopleList.stream()
.map(Person::getFirstName)
.collect(Collectors.toList());
This uses method reference syntax, which is cleaner and less error-prone. Also, consider using the newer toList() method introduced in Java 16 if you’re on a recent version:
List nameList = peopleList.stream()
.map(Person::getFirstName)
.toList();
It’s more concise and potentially more efficient. Hope this helps you get unstuck!
hey mate, looks like ur code is almost there! just a small tweak needed. try using .map(Person::getFirstName) instead of .map(person -> person.firstName). assuming u have a getter for firstName, this should work. if not, make sure to create one. good luck!