Converting a generic list to a string list using Java streams

Hey everyone! I’m trying to get the hang of Java’s stream API. I want to make a list of strings from a list of objects. Here’s what I’ve got so far:

class Human {
    String firstName;
    int yearsOld;
}

List<Human> people = getHumans();
List<String> names = people.stream().map(Human -> firstName).collect(Collectors.toList());

But it’s not working right. I’m getting a syntax error. Can someone help me figure out what I’m doing wrong? I thought this would give me a list of all the first names from my Human objects. Thanks in advance for any tips!

You’re on the right track with using streams for this task. The syntax error is in your lambda expression. Here’s the corrected version:

List<String> names = people.stream()
    .map(human -> human.firstName)
    .collect(Collectors.toList());

Remember, when accessing object properties in a lambda, you need to use the parameter name (human in this case) followed by the property (firstName). This approach works well for simple transformations. For more complex operations, consider using method references or creating a separate method. Also, if you’re using Java 16 or later, you can use the more concise toList() method instead of collect(Collectors.toList()).

hey creatingstone, ur close! the issue is in ur lambda. try changing it to:

people.stream().map(human → human.firstName).collect(Collectors.toList());

the lambda needs to reference the object (human) and then access its property (firstName). good luck with ur streams journey!

I’ve been working with Java streams for a while now, and they’re incredibly powerful once you get the hang of them. Your approach is spot on, but there’s a small tweak needed in the lambda expression.

Here’s what worked for me:

List<String> names = people.stream()
    .map(human -> human.firstName)
    .collect(Collectors.toList());

The key is to use ‘human’ as a parameter in the lambda, then access its ‘firstName’ property. This way, Java knows you’re referring to each Human object in the stream.

One pro tip: If you’re using Java 16+, you can simplify it further with:

List<String> names = people.stream()
    .map(human -> human.firstName)
    .toList();

This new toList() method is a bit more efficient. Hope this helps you on your streams journey!