We will assume that we have list of Students to convert into list of Persions .
In this article, I'm going to use functional interface call Funcation to achieve this.
Enjoy...!!
p class Student ublic { p rivate String name; private String school; private int age; public Student( S tring name, String school, int age){ t his. n ame = name; this. chool = school; this s . ge = age; a // getters/setters should come here @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", school='" + school + '\'' + ", age=" + age + '}'; } } }
public class Person{ private StringfullName; privateint age; public Person( StringfullName, int age){ this. fullName =fullName ; this. age = age;} //getters/setters should come here @Override public StringtoString() { return "Person{" + "fullName='" +fullName + '\'' + ", age='" + age + '\'' + '}'; } }
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public class StudentApplication {
public static void main(String[] args) {
Function<Student, Person> functionStuToPer = student -> new Person(student.getName(), student.getAge());
List<Student> students = Arrays.asList(
new Student("Tharanga", "UOC", 22),
new Student("Ruwan", "UOM", 24),
new Student("Ruvini", "UOK", 20),
new Student("Randika", "TOUC", 25),
new Student("Amara", "UOR", 23)
);
List<Person> persons = convertStudentListToPerson(students, functionStuToPer);
persons.forEach(System.out::println);
}
private static List<Person> convertStudentListToPerson(List<Student> students, Function<Student, Person> functions) {
List<Person> persons = new ArrayList<>();
for (Student student: students) {
persons.add(functions.apply(student));
}
return persons;
}
}
Enjoy...!!
No comments:
Post a Comment