Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coverting Java ArrayList to Vector using java Streams

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;
}
like image 509
Prasad Pande Avatar asked Sep 07 '25 14:09

Prasad Pande


2 Answers

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));
like image 131
Cardinal System Avatar answered Sep 10 '25 07:09

Cardinal System


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));
like image 39
Ousmane D. Avatar answered Sep 10 '25 05:09

Ousmane D.