I am working on a legacy code which has a List<Student> studentList
.
Each student object contains two properties:
String name;
List<Address> address;
Class Address
contains two properties houseNumber
and streetNumber
I want to create a single List which contains name, houseNumber, streetNumber
.
houseNumber
is an enum so I'll do .toString()
and an if
condition for null values.
final List<String> finalList = new ArrayList<>();
studentList
.forEach(x -> {
x.getAddressList()
.forEach(y -> {
finalList.add(x.getName);
finalList.add(y.getHouseNumber != null ?
y.getHouseNumber.toString() : "");
finalList.add(y.getStreetNumber);
});
}
);
I have written this code but I want it to achieve the result by using flatMap
.
May you want this:
var rs = lst.stream().flatMap(x -> x.getAddress().stream()
.map(y -> List.of(x.getName(),
y.getHouseNumber() != null ? y.getHouseNumber().toString() : "",
y.getStreetNumber())
)).collect(Collectors.toList());
rs
is list of list contains name, houseNumber, streetNumber.