There is a List objects of the class Person

 public class Person { String name1; String name2; String name3; String birthdate; String address; } 

How to get another from this List , but with some fields, for example, name1 , name2 and address ... Preferably, using the Stream API .

  • I like iboxdb instead of linq - Eugene Bartosh

2 answers 2

You can do this:

 List<String> fields = persons.stream() .flatMap(p -> Stream.of(p.name1, p.name2, p.address)) .collect(Collectors.toList()); 

In this case, the output list will be, and its type will be a String , not an Object .

    Solved the issue as follows:

     Object[] o = persons.stream() .map(r -> Arrays.asList(r.getName1(), r.getName2(),r.getAddress())) .toArray(); 

    Perhaps there is a better solution?

    • Better then use a collector instead of toArray , for example: List<List<String>> result = persons.stream().map(r -> Arrays.asList(r.getName1(), r.getName2(),r.getAddress())).collect(Collectors.toList()); . However, it is more convenient to work with specific types than with Object[] . - Alex Chermenin