lundi 14 février 2022

Optimized method of getting list of attributes in Java 8?

My question is an extension of this question.

To get a list of attributes we can use this code:

List<String> namesList = personList.stream()
                                   .map(Person::getAge)
                                   .collect(Collectors.toList());

However if I want to get 100 different attributes.
List<String> namesList = personList.stream()
                                   .map(Person::getName)
                                   .collect(Collectors.toList());

List<String> namesList = personList.stream()
                                   .map(Person::getSurName)
                                   .collect(Collectors.toList());

List<String> namesList = personList.stream()
                                   .map(Person::getFathersName)
                                   .collect(Collectors.toList());

List<String> namesList = personList.stream()
                                   .map(Person::getMothersName)
                                   .collect(Collectors.toList());

then would it be better to rewrite this line 100 times or should I simply run 1 loop and collect all the attributes there.

Aucun commentaire:

Enregistrer un commentaire