4

I know this is a simpler question.

But is it possible to convert given list of objects List<Person> and convert it into Vector<PersonName> using Java Streams API

public class Person {        
     String name;
     String lastName;
     int age;
     float salary;
}

public class PersonName {
     String name;
     String lastName;
}
7
  • 4
    You don't need streams: new Vector<>(list) Commented Feb 6, 2018 at 21:37
  • 1
    Why must it be made with streams? Commented Feb 6, 2018 at 21:38
  • But how will it then consider that in Vector we have only name and lastName and not age and salary? Commented Feb 6, 2018 at 21:40
  • Well, you should explain in the question that the list consists of both Persons and PersonNames. Commented Feb 6, 2018 at 21:42
  • My bad. I did frame the question same way but missed to mention that in typo. Commented Feb 6, 2018 at 21:44

2 Answers 2

9

You should really make a constructor and/or make PersonName extend Person. But here is a solution that does not use either:

ArrayList<Person> list = ...;
Vector<PersonName> vect = list.stream().map(t -> {
    PersonName name = new PersonName();
    name.lastName = t.lastName;
    name.name = t.name;
    return name;
}).collect(Collectors.toCollection(Vector::new));
Sign up to request clarification or add additional context in comments.

Comments

3

Create a two argument constructor for the PersonName type and then you can do:

Vector<PersonName> resultSet =
               peopleList.stream()
                         .map(p -> new PersonName(p.getName(), p.getLastName()))
                         .collect(Collectors.toCollection(Vector::new));

2 Comments

even better would be to create a static method for that... stream().map(Utility::transform)... also since there is just mapping, without any filtering here, it might be good to specify the initial capacity of the Vector
@Eugene I don't see why creating a static method for the transformation would be better apart from hiding the new PersonName(p.getName(), p.getLastName()) into another method. which by all means is not worthwhile to refactor to a method.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.