Thunfische :
@PostMapping("/countries")
public void createCountry(@Valid @RequestBody List<Country> countries) {
for(Country country: countries){
countryRepository.save(country);
}
Stream.of(countries)
.forEach(country -> countryRepository.save((Country)country));
}
I send this through postman
[
{
"name": "sweden",
"cities": [
{
"name": "trelleborg"
},
{
"name": "ystad"
}
]
},
{
"name": "japan",
"cities": [
{
"name": "osaka"
},
{
"name": "tokio"
}
]
}
]
With the for loop above the code works as intented, but with lambda expression below, I get this exception
java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.qweqwe.Models.Country
What is the problem? Thanks
MyTwoCents :
Stream.of
is used to build a Stream of Objects.
Since you are passing one object of type list, you get error here (Country)country
Either change Stream like this
Stream.of(countries.get(0), countries.get(1))
.forEach(country -> countryRepository.save(country));
or
countries.stream().forEach(country -> countryRepository.save(country));
I tried below test data, adding just for Reference
List<UsersDTO> lstUser = new ArrayList<>();
UsersDTO userDto1 = new UsersDTO();
userDto1.setRecordsTotal(1);
userDto1.setRecordsFiltered(3);
UsersDTO userDto2 = new UsersDTO();
userDto2.setRecordsTotal(1);
userDto2.setRecordsFiltered(2);
lstUser.add(userDto1);
lstUser.add(userDto2);
Stream.of(lstUser.get(0), lstUser.get(1))
.forEach(user -> System.out.println(user.getRecordsFiltered() ));
lstUser.stream().forEach(user -> System.out.println(user.getRecordsFiltered() ));
OUTPUT:
3
2
3
2