1

I have a class like

public class Person {

  public Person(String firstName) {...}

  public String getFirstname() {...}

  // ... some other fields

}

and a list of objects of those class:

List<Person > objList = new ArrayList<>();
objList.add(new Person("Peter"));
objList.add(new Person("James"));
objList.add(new Person("Bart"));

Now I need a comma-separated-list of the firstnames of this object-list, like "Peter,James,Bart".

How can I do this using lambdas and streams of Java 8? TIA!

1 Answer 1

11

That's basically the third example in the API documentation for java.util.stream.Collectors:

String result = objList.stream()
    .map(Person::getFirstName)
    .collect(Collectors.joining(","));
2
  • Thank you! And sorry for not seeing it in the API docs. I have read many of them and many tutorials, but I missed that one ...
    – t777
    Jul 13, 2014 at 20:58
  • @nosid I came up with this way too, but it print , at the end how can I avoid it ? objList.stream().map((s) -> s + ",").forEach(System.out::print); Jul 13, 2014 at 22:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.