简体   繁体   中英

Convert list of interface type to list of another class using Java 8

Problem: I have a list of interface type which i need to convert to list of database DTO before storing in database. I am new to Java 8 streams and map functions so any help would be great.

Research: I tried to use instanceOf in map but i always get compile errors.

Below are the different classes and their hierarchy.

public interface Animal {}

Public Class Cat implements Animal{
    private String name;
    public void getName() {
        return name;
    }
}

Public Class Dog implements Animal{
    private String name;
    public void getName() {
        return name;
    }
}

Public Class DBAnimalDTO{
    private String dbName;
    public void setDbName(String name) {
        this.dbName = name;
    }
}

To map the Dog and Cat classes i had created separate Functions.

Function<Dog, DBAnimalDTO> dogFunction = dog -> {
    DBAnimalDTO dbAnimalDTO = new DBAnimalDTO();
    dbAnimalDTO.setDbName(dog.getName());
    return dbAnimalDTO;
}
Function<Cat, DBAnimalDTO> catFunction = cat -> {
    DBAnimalDTO dbAnimalDTO = new DBAnimalDTO();
    dbAnimalDTO.setDbName(cat.getName());
    return dbAnimalDTO;
}

Using streams i tried to use different map functions based on Object type.

List<Animal> animals = new ArrayList();

List<DBAnimalDTO> dbAnimals = animals.stream().map(animal -> {
    if(animal instanceOf Dog) {
        return dogFunction;
    } else {
        return catFunction;
    }
}).collect(Collectors.<DBAnimalDTO> toList());

I always get compile issue in Collectors.toList(). How do i fix this issue?

Also, any advise on if this is a good design pattern to transform list in this scenario would also be great.

You need to apply the function that you've created as:

List<DBAnimalDTO> dbAnimals = animals.stream().map(animal -> {
    if (animal instanceof Dog) {
        return dogFunction.apply((Dog) animal);
    } else {
        return catFunction.apply((Cat) animal);
    }
}).collect(Collectors.toList());

On the other hand, using a constructor in the DBAnimalDTO class as:

public DBAnimalDTO(String dbName) {
    this.dbName = dbName;
}

you can update your functions to be more cleaner as:

Function<Dog, DBAnimalDTO> dogFunction = dog -> new DBAnimalDTO(dog.getName());
Function<Cat, DBAnimalDTO> catFunction = cat -> new DBAnimalDTO(cat.getName());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM